springboot2之系统架构基础(七.2) 发送邮件之springboot整合thymeleaf模板引擎

本章以(springboot2之系统架构基础(六) Scheduled定时任务:https://blog.csdn.net/nameIsHG/article/details/86514768)为基础,模拟定时发送邮件的一个功能

step1 导入jar包

        <!-- thymeleaf启动器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
        <!-- mail -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.1</version>
        </dependency>

step2 yml文件配置邮件站点服务器

## Spring配置:
spring: 
  http: 
    encoding:
      charset: UTF-8 
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    default-property-inclusion: NON_NULL      
  mail:
    default-encoding: UTF-8
    host: smtp.163.com   (此处使用163作为站点服务器)
    port: 25
    username: hegangjava@163.com(服务器的邮箱)
    password: 邮箱密码
    properties: 
      mail:
        smtp: 
          auth: true
          timeout: 30000
          starttls:
             enable:true
             required:true

注意是spring下的 mail

step3 创建thymeleaf模板

1·。在resource目录下创建templates目录:注意,此目录名字最好取templates

2。创建模板(我这里以html文件发形式),模板名字随意

SHEET.html

<html>
<head>
<title>订单信息</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="Content-Language" content="zh-CN"/>
<meta name="author" content="天猫商城"/>
<style class="fox_global_style">
    div.fox_html_content { line-height: 1.5; }
    div.fox_html_content { font-size: 10.5pt; font-family: 微软雅黑; color: rgb(0, 0, 0); line-height: 1.5; }
    div.fp {margin-left:20pt;}
    div.sp {margin-left:20pt;}
</style>   
</head>
<body>
<div th:utext="${userName}">用户</div>
<div class="fp">您好</div>
<div><br /></div>
<div class="fp">您于<span th:utext="${createDate}"></span>提交的订单已经生成。</div>
<div class="fp">如需进行查看详细:<a th:href="@{${exportUrl}}">点击此处下载</a>订单。</div>
<div><br /></div>

<div>
    <div class="fp">致</div>
    <div class="MsoNormal" >礼!</div>
</div>
</body>
</html>

step4  创建对象 MailData ,封装模板中动态的变量,以对象的形式进行存储(Vo)

package com.bhz.mail.vo;

import java.util.Map;

@Data
public class MailData {


	
    String userId; // 收件人
    String subject; // 邮件主题
    String from; // 邮件发送人
    String to; // 邮件收件人
    String content; // 邮件内容
    String templateName; // 邮件模板名称
    Map<String, Object> param; // 参数集(邮件模板中的动态变量值)

}

step5 创建模板引擎帮助类 GeneratorMailSendTemplateHelper

package com.bhz.mail.service;


import java.util.Locale;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import com.bhz.mail.vo.MailData;

@Service
public class GeneratorMailSendTemplateHelper {

	
	@Autowired
	private JavaMailSender javaMailSender;
	
	@Autowired
	private TemplateEngine templateEngine;
	
	public void generatorAndSend(MailData mailData) {
		try {
			//模板引擎的全局变量
			Context context = new Context();
			context.setLocale(Locale.CHINA);
			context.setVariables(mailData.getParam());
			String templateLocation = mailData.getTemplateName();
			String content = templateEngine.process(templateLocation, context);//使用模板引擎加载邮件模板
			mailData.setContent(content);
			
			send(mailData);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	
	public void send(MailData mailData) throws MessagingException {
		MimeMessage mimeMessage = javaMailSender.createMimeMessage();
		MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
		mimeMessageHelper.setFrom(mailData.getFrom());
		mimeMessageHelper.setTo(mailData.getTo());
		mimeMessageHelper.setSubject(mailData.getSubject());
		mimeMessageHelper.setText(mailData.getContent(), true);
		javaMailSender.send(mimeMessage);
	}
	
}

step6  创建service   MailSendService

package com.bhz.mail.service;

import com.bhz.mail.entity.MailSend;
import com.bhz.mail.vo.MailData;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class MailSendService {

	 @Value("${spring.mail.username}")
	 private String username;
	
	@Autowired
	private GeneratorMailSendTemplateHelper generatorMailSendTemplateHelper;
	
	
	public void sendMailInfo(MailSend mailSend) throws Exception{
		//1.准备数据
		Map<String, Object> params = new HashMap<String,Object>();
		params.put("username", mailSend.getSendUserId());
		params.put("createDate", DateFormatUtils.format(new Date(), "yy-MM-dd HH:mm:ss"));
		params.put("exportUrl","https://www.baidu.com");
		
		MailData mailData = new MailData();
		mailData.setTemplateName("SHEET");//模板的名字
		mailData.setSubject("【京东商铺邮件系统测试】");
		mailData.setFrom(username);
		mailData.setTo(mailSend.getSendTo());
		mailData.setContent(mailSend.getSendContent());
		mailData.setParam(params);
		
		generatorMailSendTemplateHelper.generatorAndSend(mailData);
		
	}
	
	
}

step7 在定时器实现中,调用service

package com.bhz.mail.task;

import com.bhz.mail.entity.MailSend;
import com.bhz.mail.service.MailSendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ConsumerMailTask {


	@Autowired
	private MailSendService mailSendService;

	/**
	 * initialDelay:项目启动的时候,延迟5秒开始执行
	 * fixedDelay:每隔10秒执行一次
	 */
	@Scheduled(initialDelay=5000,fixedDelay=10000)
	public void intervalFast(){
		try{
			MailSend mailSend  =  new MailSend();
            mailSend.setSendTo("*******@qq.com");//接收邮箱
			mailSend.setSendContent("测试内容 。。。 。。。");
			mailSendService.sendMailInfo(mailSend);
			//System.out.println("   ... ... ...  当前没有任务执行  ... ... ... ");
		}catch (Exception e){

		}
	}
	
}

MailSend 属性

private String sendId;

    private String sendUserId;

    private String sendTo;

    private Integer priority;

    private String sendContent;

    private Long sendCount;

    private String sendState;

    private String remark;

    private Long version;

    private String updateBy;

    private Date updateTime;

测试邮件成功效果截图

邮件发送及thymeleaf静态模板功能实现结合完成,不足之处,多多包涵。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值