Spring boot之邮件发送

Spring boot之邮件发送

Spring boot之邮件发送

Spring Boot中发送邮件使用的是Spring提供的org.springframework.mail.javamail.JavaMailSender,其提供了许多简单易用的方法,可发送简单的邮件、HTML格式的邮件、带附件的邮件,并且可以创建邮件模板。

引入依赖

<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>

邮件配置

server:
  port: 8888

spring:
  mail:
    # 配置 SMTP 服务器地址
    host: smtp.163.com
    # 发送者邮箱
    username: XXX@163.com
    # 配置密码,注意不是真正的密码,而是刚刚申请到的授权码
    password: JIZDEI555PKDZSVOTZQ
    # 端口号:465或者994
    port: 465
    protocol: smtps
    properties:
      mail:
        # 表示开启 DEBUG 模式
        debug: true
        smtp:
          socketFactoryClass: javax.net.ssl.SSLSocketFactory
          auth: true
          starttls:
            enable: true
            required: true

发送简单的邮件

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

    @Autowired
    private JavaMailSender jms;

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

    @RequestMapping("sendSimpleEmail")
    public String sendSimpleEmail() {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            // 接收地址
            message.setTo("XXX@onmicrosoft.com");
            // 标题
            message.setSubject("一封简单的邮件");
            // 内容
            message.setText("使用Spring Boot发送简单邮件。");
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}

发送HTML格式的邮件

    @RequestMapping("sendHtmlEmail")
    public String sendHtmlEmail() {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo("XXX@onmicrosoft.com");
            helper.setSubject("一封HTML格式的邮件");
            // 带HTML格式的内容
            StringBuffer sb = new StringBuffer("<p style='color:#42b983'>使用Spring Boot发送HTML格式邮件。</p>");
            helper.setText(sb.toString(), true);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

发送带附件的邮件

    @RequestMapping("sendAttachmentsMail")
    public String sendAttachmentsMail() {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo("XXX@onmicrosoft.com");
            helper.setSubject("一封带附件的邮件");
            helper.setText("详情参见附件内容!");
            // 传入附件
            File file = ResourceUtils.getFile("classpath:static/file/附件.docx");
            helper.addAttachment("附件.docx", file);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

发送带静态资源的邮件

    @RequestMapping("sendInlineMail")
    public String sendInlineMail() {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo("XXX@onmicrosoft.com");
            helper.setSubject("一封带静态资源的邮件"); // 标题
            helper.setText("<html><body>图片:<img src='cid:img'/></body></html>", true);
            // 传入附件
            File file = ResourceUtils.getFile("classpath:static/img/img.png");
            helper.addInline("img", file);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

使用模板发送邮件

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>模板</title>
</head>
<body>
    您好,您的验证码为<span th:text="${code}"></span>,请在两分钟内使用完成操作。
</body>
</html>
	 @Autowired
    private TemplateEngine templateEngine;

    @RequestMapping("sendTemplateEmail")
    public String sendTemplateEmail(String code) {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo("XXX@onmicrosoft.com"); // 接收地址
            helper.setSubject("邮件摸板测试"); // 标题
            // 处理邮件模板
            Context context = new Context();
            context.setVariable("code", code);
            String template = templateEngine.process("emailTemplate", context);
            helper.setText(template, true);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
上一篇:Springboot异步、邮件发送、定时任务


下一篇:MVC之AJAX异步提交表单