项目需求:邮件异步发送结果给用户
项目框架:SpringBoot
实现:
- 第一步:
在pom文件中导入相关的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- 第二步:
编写发送邮件的工具类,并在配置文件中配置邮箱服务器地址
@Component
public class SendEmailTool {
@Autowired
JavaMailSender jms;
@Value("${spring.mail.username}")
String sendUserEmail;
/**
* 发送邮件
* @param data 加密主体
*/
@Async
public void sendEmail(String data){
//建立邮件消息
SimpleMailMessage mainMessage = new SimpleMailMessage();
//发送者
mainMessage.setFrom(sendUserEmail);
//接收者
mainMessage.setTo("xxx@xxx.com.cn");
//发送的标题
mainMessage.setSubject("用户信息");
String content = "尊敬的用户: \n"+
"\r\n"+
" 您好! \n";
mainMessage.setText(content);
jms.send(mainMessage);
System.out.println("用户信息已成功发送至邮箱");
}
}
配置文件,使用126邮箱,其他邮箱自行百度
spring.mail.host=smtp.126.com
spring.mail.port=465
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.username=xxx@126.com
spring.mail.password=password
spring.mail.default-encoding=UTF-8
spring.mail.protocol=smtp
踩坑:
1 Could not autowire. No beans of ‘JavaMailSender’ type found.
debug会报空指针异常
解决:
1 把@Autowirde改成@Resource
相同点:
@Resource的作用相当于@Autowired,均可标注在字段或属性的setter方法上。不同点:
(1)提供方:@Autowired是由org.springframework.beans.factory.annotation.Autowired提供,换句话说就是由Spring提供;@Resource是由javax.annotation.Resource提供,即J2EE提供,需要JDK1.6及以上。
(2)注入方式:@Autowired只按照byType 注入;@Resource默认按byName自动注入,也提供按照byType 注入;
(3)属性 :@Autowired按类型装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它required属性为false。如果我们想使用按名称装配,可以结合@Qualifier注解一起使用。@Resource有两个中重要的属性:name和type。name属性指定byName,如果没有指定name属性,当注解标注在字段上,即默认取字段的名称作为bean名称寻找依赖对象,当注解标注在属性的setter方法上,即默认取属性名作为bean名称寻找依赖对象。需要注意的是,@Resource如果没有指定name属性,并且按照默认的名称仍然找不到依赖对象时,
@Resource注解会回退到按类型装配。但一旦指定了name属性,就只能按名称装配了。
2 使用@Autowired(required=false)
- 第三步:查看邮件是否异步发送
在主线程和发送邮件的方法中加入如下代码:
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
启动项目测试结果:
异步执行成功!