码迷,mamicode.com
首页 > 编程语言 > 详细

springboot(8) 发送邮件

时间:2020-07-03 21:01:25      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:需要   exception   context   encoding   templates   名称   wired   frame   receiver   

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(8) 发送邮件

标签:需要   exception   context   encoding   templates   名称   wired   frame   receiver   

原文地址:https://www.cnblogs.com/t96fxi/p/13232595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!