Maven配置:

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

application.properties配置:

# 配置网易163邮箱
spring.mail.username=账号
spring.mail.password=授权码
spring.mail.host=smtp.163.com

# 配置QQ邮箱
#spring.mail.username=XXXX
#spring.mail.password=XXXX
#spring.mail.host=smtp.qq.com
# 开启安全连接
#spring.mail.properties.mail.smtp.ssl.enable=true

开启以下选项:

设置授权码:

发送纯文本Email:

    @Autowired
    JavaMailSender mailSender;


    @Test
    public void test1() {
        SimpleMailMessage message = new SimpleMailMessage();
        // 邮件发送人
        message.setFrom("[email protected]");
        // 邮件接收人
        message.setTo("[email protected]");
        // 邮件标题啊
        message.setSubject("通知:开会");
        // 邮件内容
        message.setText("1点开会");
        mailSender.send(message);
    }

发送带附件的Email:

    @Test
    public void test2() throws MessagingException {
        // 1、创建复杂的邮件消息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 设置true--代表上传图片
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        // 邮件标题啊
        // 邮件发送人
        helper.setFrom("[email protected]");
        // 邮件接收人
        helper.setTo("[email protected]");
        helper.setSubject("通知:今晚开会");
        // 邮件内容--设置true HTML才可以生效
        helper.setText("<b>今天 1:10 开会</b>",true);
        // 上传文件
        helper.addAttachment("1.jpg", new File("C:\\Users\\MyPC\\Desktop\\xiaofei\\图标\\1.jpg"));
        mailSender.send(mimeMessage);
    }

发送Thymeleaf的Email:

    @Test
    public void sendReplyEmail() {
        String subject = "XFBlog博客邮件通知";
        Context context = new Context();
        context.setVariable("count", "内容");
        // 指定相应的模板
        String templateContext = templateEngine.process("email/replyEmailTemplate", context);
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(templateContext, true);
            mailSender.send(message);
            log.info("send email {} to {} success ", templateContext, to);
        } catch (MessagingException e) {
            log.error("send email {} to {} failed {},{}", templateContext, to, e.getMessage(), e);
        }
    }

Thymeleaf:


<!DOCTYPE html>
<html lang="zh" xmlns:th="https://www.thymeleaf.org">
<body>
    <sapn th:text="${count}"></sapn>
</body>
</html>