spring自带JavaMailSender发送邮件

spring自带的MailSender类在spring-context-support-xxx.RELEASE.jar文件中,这里以4.3.4版本为例。

1、新建gradle项目,引入依赖配置。

 compile group:"org.springframework",name:"spring-context-support",version:"4.3.4.RELEASE"
 compile group:"javax.mail",name:"mail",version:"1.4.7"

2、编写发送邮件服务类。

package com.xx.sendmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
public class MailSenderService {
	
	@Autowired
	private JavaMailSender mailSender;
	
	public void send(SimpleMailMessage message){
		mailSender.send(message);
		System.out.println("send message successfully.");
	}
}

3、新建配置文件applicationContext.xml与mail.properties。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
                            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
	<bean id="propertyConfigurer" 
           class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	     <property name="locations">
	          <value>mail.properties</value>
	     </property>
	</bean>
	<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	     <property name="host" value="${mail.host}"></property>
	     <property name="javaMailProperties">
	          <props>
	                <prop key="mail.smtp.auth">true</prop>
	                <prop key="mail.smtp.timeout">25000</prop>
	                <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
	                <prop key="mail.smtp.starttls.enable">true</prop>
	          </props>
	     </property>
	     <property name="username" value="${mail.username}"></property>
	     <property name="password" value="${mail.password}"></property>
	     <property name="port" value="${mail.port}"></property>
	</bean>
	<bean id="mailSenderService" class="com.xx.sendmail.MailSenderService"></bean>
</beans>

mail.properties,我这里使用的是126邮箱作为测试邮箱,因此,密码这里需要使用客户端授权码。

mail.host=smtp.126.com
mail.username=y******9@126.com
mail.password=y******2//这里是客户端授权码,不是邮箱登录密码
mail.port=465

4、编写测试邮件发送程序。

package com.xx.sendmail;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;
public class Application {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
                                                         new String[]{"applicationContext.xml"});
		MailSenderService senderService = (MailSenderService)context.getBean("mailSenderService");
		SimpleMailMessage mail = new SimpleMailMessage();
		mail.setTo("******5@sina.com");
		mail.setFrom("y******9@126.com");
		mail.setSubject("spring sendmail test");
		mail.setText("Hello,***,this is my test,do not reply.");
		
		senderService.send(mail);
	}
}

运行,如果配置均正确,就会看到打印send message successfully.然后去收件箱检查,发现邮件一封。


这里如果设置邮箱服务器的密码不是客户端授权码,那么可能会遇到以下错误。

Exception in thread "main" org.springframework.mail.MailAuthenticationException: Authentication failed; 
nested exception is javax.mail.AuthenticationFailedException: 535 Error: authentication failed

这个问题在126邮箱设置中有明确说明:


使用 Java 实现发送海外邮件,需要完成一些准备工作并编写相应代码。 ### 准备工作 在使用 Java 发送邮件之前,需要在机器上安装 JavaMail API 和 Java Activation Framework (JAF)。可以从 Java 网站下载最新版本的 JavaMail,打开网页右侧有个 Downloads 链接,点击它下载;也可以从 Java 网站下载最新版本的 JAF(版本 1.1.1)[^3]。 ### 代码实现 以下是一个使用 Java 发送海外邮件的示例代码,使用 Spring 框架中的 `JavaMailSender` 来实现: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; /*JAVA自带邮件服务*/ @Component public class EmailUtils { private final JavaMailSender javaMailSender; private final String emailFrom; public EmailUtils(JavaMailSender javaMailSender, @Value("${email.from}") String emailFrom) { this.javaMailSender = javaMailSender; this.emailFrom = emailFrom; } public void sendEmails(String email) { try { // 创建复杂邮件对象 MimeMessage mimeMessage = javaMailSender.createMimeMessage(); // 发送复杂邮件的工具类 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8"); helper.setFrom(emailFrom); helper.setSubject("邮件标题"); helper.setText("<h1>邮件内容</h1>", true); // 收件人 helper.setTo(email); javaMailSender.send(mimeMessage); } catch (MessagingException e) { e.printStackTrace(); } } } ``` 在上述代码中,`EmailUtils` 类封装了发送邮件的逻辑。`sendEmails` 方法接收一个收件人的邮箱地址作为参数,创建一个复杂邮件对象,设置邮件的发件人、主题、内容和收件人,最后使用 `JavaMailSender` 发送邮件。 ### 配置文件 在 `application.properties` 或 `application.yml` 中添加邮件相关的配置: ```properties spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=your_email@example.com spring.mail.password=your_email_password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true email.from=your_email@example.com ``` 请将 `smtp.example.com` 替换为实际的 SMTP 服务器地址,`your_email@example.com` 替换为发件人的邮箱地址,`your_email_password` 替换为发件人的邮箱密码。 ### 超时设置 为了避免因发送失败导致系统崩溃,可以设置发送失败的超时时间。例如设置 5 秒内发不成功就退出,并打印日志或发送告警信息进行人工介入处理 [^5]。 ### 注意事项 - 确保发件人的邮箱开启了 SMTP 服务,并获取了正确的 SMTP 服务器地址和端口。 - 部分海外邮箱可能需要进行额外的配置或验证,如 Gmail 可能需要开启“允许不太安全的应用访问”或使用应用专用密码。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luffy5459

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值