Springboot集成JavaMailSender发送邮件

项目需求:邮件异步发送结果给用户
项目框架: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);

启动项目测试结果:
在这里插入图片描述
异步执行成功!

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值