springboot 发送邮件

Posted haohao1234

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot 发送邮件相关的知识,希望对你有一定的参考价值。

1、pom.xml

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

application.properties

server.port=8083
spring.mail.host=smtp.qq.com
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.password=kjamgrjlonmnbgaa  #这个是授权码,不是邮箱密码
spring.mail.username=805755@qq.com
spring.mail.port=587
spring.mail.properties.mail.stmp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true

邮件模板

resource/templates/mail.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>提示邮件</title>
</head>
<body>
有新的Banner创建成功
<table border="1">
    <tr>
        <td>Id</td>
        <td th:text="${bannerId}"></td>
    </tr>
    <tr>
        <td>名称</td>
        <td th:text="${bannerName}"></td>
    </tr>
    <tr>
        <td>创建时间</td>
        <td th:text="${createTime}"></td>
    </tr>
</table>

<p>希望在未来的日子里,携手共进!</p>
</body>
</html>

发送邮件

@Component
public class MailReceiver {
    public static final Logger logger = LoggerFactory.getLogger(MailReceiver.class);
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    MailProperties mailProperties;
    @Autowired
    TemplateEngine templateEngine;

    @RabbitListener(queues = Const.MAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel){
        Long tag = null;
        try {
            Banner banner = (Banner) message.getPayload();// 发送邮件
            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(msg);
            helper.setTo("805766@qq.com");
            helper.setFrom("805755@qq.com"); // 这个需要和spring.mail.username一致
            helper.setSubject("创建Banner");
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("bannerId", banner.getId());
            context.setVariable("bannerName", banner.getBannerName());
            context.setVariable("createTime", banner.getCreateTime());
            String mail = templateEngine.process("mail", context);
            helper.setText(mail, true);
            javaMailSender.send(msg);
          
            logger.info("邮件发送成功");
        } catch (Exception e) {
            
            logger.error("邮件发送失败");
        }
    }
}

 

以上是关于springboot 发送邮件的主要内容,如果未能解决你的问题,请参考以下文章

25springboot发送邮件

25springboot发送邮件

补习系列(12)-springboot 与邮件发送

使用SpringBoot发送mail邮件

java springboot+maven发送邮件

SpringBoot定时发送邮件