依赖文件

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

配置文件

# email
spring.mail.host=smtp.sina.com
[email protected]
spring.mail.password=81ce7013c83817d6
spring.mail.properties.mail.smtl.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

发送邮件类

@Component
public class MailClient {
    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

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

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

发送邮件

@SpringBootTest
@ContextConfiguration(classes = NowcoderApplication.class)
public class MailTests {
    @Autowired
    private MailClient mailClient;

    @Autowired
    TemplateEngine templateEngine;

    // 直接发送
    @Test
    public void testTextMail() {
        mailClient.sendMail("[email protected]", "Test", "Welcome.");
    }

    // 通过HTML模板进行发送
    @Test
    public void testHTMLMail() {
        Context context = new Context();
        context.setVariable("username", "sunday");

        String content = templateEngine.process("/mail/demo.html", context);
        System.out.println(content);

        mailClient.sendMail("[email protected]", "Test", content);
    }
}