Spring Boot 使用 JavaMailSender发送邮件

新建spring boot 应用

通过Spring Initializr 新建一个spring boot 应用,然后在idea中打开,在原有pom中额外添加如下依赖:

        <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>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

创建配置文件

resources/application.properties

#mail
spring.mail.host=smtp.163.com
spring.mail.username=修改成自己邮箱账号
spring.mail.password=修改成自己邮箱密码
spring.mail.default-encoding=UTF-8

#thymeleaf
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.vm
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false

邮件模版,模版中有一个变量username
resources/templates/email-template.vm

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Java Mail</title>
</head>
<body>
<h3>你好:<span th:text="${username}"></span></h3>
<p>welcome to use thymeleaf.</p>
</body>
</html>

创建领域对象

@Data
public class MailMessage {

    /**
     * 邮件模版
     */
    private String templateId;

    /**
     * 邮件变量
     */
    private Map<String, Object> paramMap;

    /**
     * 邮件主题
     */
    private String subject;

    /**
     * 发送者
     */
    private String from;

    /**
     * 抄送
     */
    private List<String> copyList;

    /**
     * 接收者
     */
    private List<String> toList;
}

创建服务

public interface MailService {

    boolean send(MailMessage message);

}

创建服务实现

@Service
public class MailServiceImpl implements MailService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    private JavaMailSender sender;

    @Autowired
    private SpringTemplateEngine templateEngine;

    /**
     * https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/integration.html#mail-usage-mime
     *
     * @param message
     * @return
     */
    @Override
    public boolean send(MailMessage message) {
        // TODO 参数校验...

        try {
            //构造消息
            MimeMessage mimeMessage = buildMimeMessage(message);
            //发送
            sender.send(mimeMessage);
        } catch (Exception e) {
            LOGGER.error("send mail error", e);
            return false;
        }
        return true;
    }

    private MimeMessage buildMimeMessage(MailMessage message) throws Exception {
        MimeMessage mimeMessage = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        //主题
        helper.setSubject(message.getSubject());
        //发送者
        helper.setFrom(message.getFrom());
        //接受者
        helper.setTo(message.getToList().toArray(new String[0]));

        //抄送
        if (!CollectionUtils.isEmpty(message.getCopyList())) {
            helper.setCc(message.getCopyList().toArray(new String[0]));
        }

        Context context = new Context(Locale.CHINA);
        context.setVariables(message.getParamMap());
        //解析模版
        String content = templateEngine.process(message.getTemplateId(), context);
        helper.setText(content, true);

        return mimeMessage;
    }
}

启动应用

@SpringBootApplication
public class MailApplication implements CommandLineRunner {

    @Autowired
    private MailService mailService;

    public static void main(String[] args) {
        SpringApplication.run(MailApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        MailMessage mailMessage = new MailMessage();
        mailMessage.setTemplateId("email-template");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("username", "张三");
        mailMessage.setParamMap(paramMap);

        mailMessage.setFrom("修改成发送者邮箱");
        mailMessage.setToList(Arrays.asList("修改成接收者邮箱"));
        mailMessage.setSubject("Hello Spring Boot Java Mail");

        mailService.send(mailMessage);
    }
}

检查接收者邮箱

可以看到已经收到了邮件,并且模版中的username也替换成了: “张三”
邮件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值