Spring中使用JavaMailSenderImpl进行邮件发送

本文介绍了如何在Spring项目中使用JavaMailSenderImpl进行邮件发送。首先,需要引入必要的jar包,如mail.jar和spring-context-support。然后,配置applicationContext.xml,设置邮件服务器的相关属性。通过这样的配置,可以实现在Spring应用中发送电子邮件的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先项目除了Spring本身必须的包外,还必须添加java提供的mail.jar以及Spring依赖的spring-context-support-4.0.0.RELEASE.jar包,mail.jar下载地址:mail.jar下载链接

第一步配置applicationContext.xml如下:

<!-- 邮件发送 -->
	<bean id="javaMailSenderImpl" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host" value="${mail.smtp.host}"></property>
		<property name="username" value="${mail.smtp.username}"></property>
		<property name="password" value="${mail.smtp.password}"></property>
	    <!-- 相当于javax.mail.Session中的props属性-->
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
				<prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
				<prop key="mail.smtp.from">${mail.smtp.from}</prop>
			</props>
		</property>
	</bean>
propertiies配置如下:

mail.smtp.host=stmp.163.com
mail.smtp.auth=true
mail.smtp.timeout=25000
mail.smtp.from=fromUser@163.com
mail.smtp.username=userLoginName
mail.smtp.password=userLoginPassword
java代码:
package com.hubu.wk;

import java.io.File;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class MainTest {

	@Resource
	private static JavaMailSenderImpl javaMailSenderImpl;

	/**
	 * 
	 * @param toEmail 收件人
	 * @param subject 邮件主题
	 * @param content 邮件内容
	 * @param filePath 附件路径
	 * @throws MessagingException
	 */
	public static void sendHtmlMail(String toEmail, String subject,
			String content, String filePath) throws MessagingException {
		MimeMessage mailMessage = javaMailSenderImpl.createMimeMessage();
		MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,
				true, "utf-8");
		// 设置收件人
		messageHelper.setTo(toEmail);
		messageHelper.setSubject(subject);// 标题
		// true 表示启动HTML格式的邮件
		messageHelper.setText(content, true);
		if(null!=filePath){
			FileSystemResource file = new FileSystemResource(new File(filePath));
			if(file.exists()){
				// 这里的方法调用和插入图片是不同的。
				messageHelper.addAttachment("test.doc", file);
//				messageHelper.addInline("imgName", file);//插入图片需调用此方法
			}
		}
		// 发送邮件
		javaMailSenderImpl.send(mailMessage);
	}

}

Spring的IOC容器会根据@Resource注解自动将javaMailSenderImpl注入进来



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值