springboot中JavaMailSender发送邮件

      最近这两天做个邮件发送功能,个人想着用下第三方的平台,比如说submail,阿里云等等,然后为了节约成本自己使用javaMail去做吧,下面是用qq邮箱做测试的,做个记录,能用到的就用吧,一般都会用第三方的,稳定,高效...

       Spring提供了非常好用的JavaMailSender接口实现邮件发送。在Spring Boot的Starter模块中也为此提供了自动化配置。下面通过实例看看如何在Spring Boot中使用JavaMailSender发送邮件。

上代码:

 pom.xml文件配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

接下来配置属性值,使用zookeeper自己去找配置,差不多,这里是bootstrap-dev.properties配置属性

#邮件发送
spring.mail.host=smtp.qq.com
spring.mail.username=邮箱
#这个授权码自己获取,开通邮件协议,没开通的话启动项目会报535认证失败
spring.mail.password=授权码  
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

注意:若使用QQ邮箱发送邮件,则需要修改为spring.mail.host=smtp.qq.com,同时spring.mail.password改为QQ邮箱的授权码。 
QQ邮箱->设置->账户->POP3/SMTP服务:开启服务后会获得QQ的授权码 
这里写图片描述 

发送简单文本邮件代码:

//日志
private Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

@Autowired
private JavaMailSender mailSender;

@Override
public Map sendMail() throws Exception {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom("[email protected]");
    message.setTo("[email protected]");
    message.setSubject("主题:简单邮件");
    message.setText("测试邮件内容");

    mailSender.send(message);

    return null;
}

发送简单的文本邮件已经可以了,现在太忙,后面发送附件,静态资源等等的,下一篇上代码

猜你喜欢

转载自blog.csdn.net/kaola_l/article/details/81121615
今日推荐