SpringBoot发送邮件

警告
本文最后更新于 2023-03-19,文中内容可能已过时,请谨慎使用。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

编写EmailController,注入JavaMailSender

@RestController
@RequestMapping("/email")
public class EmailController {

    @Resource
    private JavaMailSender jms;
    
    @Value("${spring.mail.username}")
    private String from;
    
    @GetMapping("sendSimpleEmail")
    public String sendSimpleEmail() {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            // 收件方
            message.setTo("xxx@qq.com"); 
            // 标题
            message.setSubject("一封简单的邮件"); 
            // 内容
            message.setText("使用Spring Boot发送简单邮件。"); 
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}

邮箱配置: 以163邮箱为例

spring:
  mail:
    host: smtp.163.com
    username: 邮箱名
    password: 邮箱授权码
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
/images/all/image-20230319201635264.png
接口测试成功
/images/all/image-20230319203014191.png
发送成功

SimpleMailMessage替换为MimeMessage

@GetMapping("sendHtmlEmail")
public String sendHtmlEmail() {
    MimeMessage message = null;
    try {
        message = jms.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        // 收件方
        helper.setTo("xxx@qq.com"); 
        // 标题
        helper.setSubject("一封HTML格式的邮件"); 
        // 带HTML格式的内容
        StringBuffer sb = new StringBuffer("<p style='color:#6db33f'>使用Spring Boot发送HTML格式邮件。</p>");
        helper.setText(sb.toString(), true);
        jms.send(message);
        return "发送成功";
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
}
/images/all/image-20230319204206435.png
发送成功

发送带附件的邮件和普通邮件相比,其实就只是多了个传入附件的过程。不过使用的仍是MimeMessage

 @GetMapping("sendAttachmentsMail")
    public String sendAttachmentsMail() {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            // 收件方
            helper.setTo("xxx@qq.com");
            // 标题
            helper.setSubject("一封带附件的邮件");
            // 内容
            helper.setText("详情参见附件内容!"); 
            // 传入附件
            FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/test.txt"));
            // 附件的名字
            helper.addAttachment("test.txt", file);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
/images/all/image-20230319205025710.png
发送成功
@GetMapping("sendInlineMail")
public String sendInlineMail() {
    MimeMessage message = null;
    try {
        message = jms.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        // 接收地址
        helper.setTo("xxx@qq.com");
        // 标题
        helper.setSubject("一封带静态资源的邮件");
        // 内容
        helper.setText("<html><body><h2>图片:</h2><img src='cid:myImg'/></body></html>", true);
        // 传入附件
        FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/1679230591682.jpg"));
        helper.addInline("myImg", file);
        jms.send(message);
        return "发送成功";
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
/images/all/image-20230319210154004.png
发送成功

引入模板引擎thymeleaf的依赖

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

template目录下创建一个emailTemplate.html模板:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>验证码模板</title>
</head>
<body>
您好,本次验证的验证码为:<span style="font-weight: bolder;color: red" th:text="${code}"></span>
</body>
</html>

发送模板邮件,本质上还是发送HTML邮件,不过加上给模板引擎传值的步骤

@Autowired
private TemplateEngine templateEngine;

@PostMapping("sendTemplateEmail")
public String sendTemplateEmail() {
    MimeMessage message = null;
    try {
        message = jms.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 设置发件人
        helper.setFrom(from);
        // 收件人
        helper.setTo("xxx@qq.com");
        // 标题
        helper.setSubject("发送验证码");
        // 处理邮件模板
        Context context = new Context();
        // 使用工具类生成验证码,将code传递给模板
        context.setVariable("code", VerCodeGenerateUtil.generateVerCode());
        // 对应上面的emailTemplate.html
        String template = templateEngine.process("emailTemplate", context);
        helper.setText(template, true);
        jms.send(message);
        return "发送成功";
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
}

验证码生成工具类:

/**
 * 验证码生成
 */
public class VerCodeGenerateUtil {
    //验证码包含的字段,可自己设置
    private static final String SYMBOLS = "0123456789" +
            "abcdefghijkomnopqrstuvwxyz" +
            "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
    // 验证码位数
    public static final Integer CODE_NUMBER = 4;
    private static final Random RANDOM = new SecureRandom();

    public static String generateVerCode() {
        char[] numbers = new char[CODE_NUMBER];
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(numbers);
    }
}
/images/all/image-20230319214647516.png
发送成功

相关文章