0%

Spring Boot Starter Mail使用

  • 导入jar包

  • 邮箱参数配置

    1
    2
    3
    4
    5
    6
    7
    #Spring Boot Starter Mail
    spring.mail.host=smtp.qq.com
    spring.mail.port=465
    spring.mail.username=邮箱
    spring.mail.password=授权码
    spring.mail.protocol=smtps
    spring.mail.properties.mail.smtp.ssl.enable=true
  • 使用JavaMailSender发送邮件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to, String subject, String content) {
    try {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    mailSender.send(helper.getMimeMessage());
    } catch (MessagingException e) {
    logger.error("发送邮件失败:" + e.getMessage());
    }
    }

使用Thymeleaf发送HTML文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Autowired
private MailClient mailClient;

@Autowired
private TemplateEngine templateEngine;

@Test
public void testHtmlMail() {
Context context = new Context();
context.setVariable("username", "sunday");

String content = templateEngine.process("/mail/activation", context);
mailClient.sendMail("abc@qq.com", "测试邮件", content);
}
------ THEEND ------

欢迎关注我的其它发布渠道