Spring Boot 发送邮件(Thymeleaf 构建邮件模版)

一、pom

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

<!-- thymeleaf 模板 -->
<dependency>
	<groupId>org.thymeleaf</groupId>
	<artifactId>thymeleaf</artifactId>
</dependency>

二、yml

spring:
  # 邮件服务
  # qq    host: smtp.qq.com,    port: 465/587
  # 126   host: smtp.126.com,   port: 465/994
  # 163   host: smtp.163.com,   port: 465/994
  # yeah  host: smtp.yeah.net,  port: 465/994
  mail:
    # 配置 SMTP 服务器地址
    host: smtp.qq.com
    # 发送者邮箱
    username: 76*******@qq.com
    # 配置密码,注意不是真正的密码,而是刚刚申请到的授权码
    password: kl**************
    # 端口号465或587
    port: 587
    # 默认的邮件编码为UTF-8
    default-encoding: UTF-8
    # 解析页
    thymeleaf-html: exchange.html
    # 标题
    subject: 这是一封测试邮件
    # 配置SSL 加密工厂
    properties:
      mail:
        smtp:
          socketFactoryClass: javax.net.ssl.SSLSocketFactory
          starttls:
            enable: true
            required: true
        ssl:
          enable: true
        # 表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
        debug: true

三、静态注入(两种方式)

@Component
public class EmailUtils {

	// 方式一 - @PostConstruct
	
	/**
     * 自动配置邮件发送
     */
    @Autowired
    private JavaMailSender javaMailSender;
    private static JavaMailSender SjavaMailSender;
    
	/**
     * 发送人邮箱
     */
    @Value("${spring.mail.username}")
    private String from;
    private static String Sfrom;

	@PostConstruct
    private void init() {
    	SjavaMailSender= javaMailSender;
        Sfrom = from;
    }

	// 方式二 - SET
	// 注:set 方法不能有 static
	
    /**
     * 自动配置邮件发送
     */
    private static JavaMailSender javaMailSender;

    @Autowired
    private void setJavaMailSender(JavaMailSender javaMailSender) {
        EmailUtils.javaMailSender = javaMailSender;
    }

    /**
     * 发送人邮箱
     */
    private static String from;

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

四、EmailUtils(完整代码 - Thymeleaf)

package com.*.*.utils;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.util.MapUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author NingZe
 * description: email utils
 * path: com.*.*.utils-EmailUtils
 * date: 2021/4/8 15:49
 * version: 02.06
 * To change this template use File | Settings | File Templates.
 */
@Component
public class EmailUtils {

    /**
     * 自动配置邮件发送
     */
    private static JavaMailSender javaMailSender;

    @Autowired
    private void setJavaMailSender(JavaMailSender javaMailSender) {
        EmailUtils.javaMailSender = javaMailSender;
    }

    /**
     * 自动配置模版引擎
     */
    private static TemplateEngine templateEngine;

    @Autowired
    private void setTemplateEngine(TemplateEngine templateEngine) {
        EmailUtils.templateEngine = templateEngine;
    }

    /**
     * 发送人邮箱
     */
    private static String from;

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

    /**
     * 解析页
     */
    private static String html;

    @Value("${spring.mail.thymeleaf-html}")
    private void setHtml(String html) {
        EmailUtils.html = html;
    }

    /**
     * 标题
     */
    private static String subject;

    @Value("${spring.mail.subject}")
    private void setSubject(String subject) {
        EmailUtils.subject = subject;
    }

    /**
     * 普通发送邮件
     *
     * @param text
     * @param toMails
     * @throws MessagingException
     */
    public static int sendSimpleMail(String text, String... toMails) {
        // text or toMails is null
        if (StringUtils.isEmpty(text) || ArrayUtils.isEmpty(toMails)) {
            return 0;
        }
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject(subject);
            message.setFrom(from);
            message.setBcc(from);
            message.setTo(toMails);
            message.setText(text);
            javaMailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    /**
     * 发送 thymeleaf 页面邮件 - 单参数
     *
     * @param goldCoinCode
     * @param toMails
     * @throws MessagingException
     */
    public static int sendThymeleafMail(String goldCoinCode, String... toMails) {
        // goldCoinCode is null
        if (StringUtils.isEmpty(goldCoinCode)) {
            return 0;
        }
        // 发送邮件
        return sendThymeleafMail(null, goldCoinCode, toMails);
    }

    /**
     * 发送 thymeleaf 页面邮件 - 多参数
     *
     * @param map
     * @param toMails
     * @throws MessagingException
     */
    public static int sendThymeleafMail(Map<String, Object> map, String... toMails) {
        // map is null
        if (MapUtils.isEmpty(map)) {
            return 0;
        }
        // 发送邮件
        return sendThymeleafMail(map, null, toMails);
    }

    /**
     * 发送 thymeleaf 页面邮件 - 最终执行
     *
     * @param map
     * @param toMails
     * @throws MessagingException
     */
    private static int sendThymeleafMail(Map<String, Object> map, String goldCoinCode, String... toMails) {
        // toMails is null
        if (ArrayUtils.isEmpty(toMails)) {
            return 0;
        }
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setSubject(subject);
            helper.setFrom(from);
            helper.setBcc(from);
            helper.setTo(toMails);
            Context context = new Context();
            if (!MapUtils.isEmpty(map)) {
                context.setVariables(map);
            } else {
                context.setVariable("GoldCoinCode", goldCoinCode);
            }
            String process = templateEngine.process(html, context);
            helper.setText(process,true);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

}

五、exchange.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>exchange</title>
</head>
<style>
    body {
        cursor: default;
    }

    .exchangeCode {
        color: #72cdff;
    }
</style>
<body>
<div>
    <label>ExchangeCode:</label>
    <div class="exchangeCode" th:text="${GoldCoinCode}"></div>
</div>
</body>
</html>

六、测试

public static void main(String[] args) {
    
    // 发送 Thymeleaf 模版邮件
	EmailUtils.sendThymeleafMail("SHKSJSDFHHJKJK", "76******42@qq.com");
        
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值