spingboot 邮件模板发送;

 <!-- 邮件start -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<!-- 邮件end -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--freemarker模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--quartz定时-->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
-------------------------------------------------------------------
# JavaMailSender 邮件发送的配置s
spring.mail.host=smtp.qq.com
[email protected]
spring.mail.password=klfrwbbhd
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
# JavaMailSender 邮件发送的配置e
#每60执行一次
scheduled.cron=0/60 * * * * ?
#初次执行任务之前需要等待的时间(5秒)
scheduled.initialDelay=60000
#每次执行任务之后间隔多久再次执行该任务(60秒)执行频率
scheduled.fixedDelay=60000
#执行频率,每隔多少时间就启动任务,不管该任务是否启动完成
scheduled.fixedRate=60000
----------------------------------------------------------------
package com.manage.util;


import com.w3china.mingjing3.model.MailLog;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;

import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

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

public class Singleton { //双检锁/双重校验锁(单例模式)
private static final Logger LOGGER = LoggerFactory.getLogger(Singleton.class);

private static class SingletonHolder {
public final static Singleton instance = new Singleton();
}

public static Singleton getInstance() {
return SingletonHolder.instance;
}

public static Map<Object, Object> sendmail(MailLog mailLog, JavaMailSender mailSender, String mailFrom, String password, FreeMarkerConfigurer freeMarkerConfigurer) {
Map<Object, Object> map = new HashMap<Object, Object>();
// 发邮件
MimeMessage message = null;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(mailFrom);
helper.setTo(mailLog.getMailTo());
helper.setSubject(mailLog.getRefAction());
Map<String, Object> model = new HashMap<>();
String mailtemplatsPath = "";
if (103 == mailLog.getResType()) {
model.put("resTypeName", "服务资源");
} else if (102 == mailLog.getResType()) {
model.put("resTypeName", "云资源");
} else if (101 == mailLog.getResType()) {
model.put("resTypeName", "广告资源");
}
model.put("refName", mailLog.getRefName());
model.put("refQuota", mailLog.getRefQuota());
if ((mailLog.getRefAction()).equals("额度发放")) {
mailtemplatsPath = "mailtemplats/sendQuota.ftl";
} else if ((mailLog.getRefAction()).equals("额度使用")) {
mailtemplatsPath = "mailtemplats/useQuota.ftl";
} else if ((mailLog.getRefAction()).equals("额度返还")) {
mailtemplatsPath = "mailtemplats/backQuota.ftl";
}
//读取 ftl 模板
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(mailtemplatsPath);
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
helper.setText(html, true);
map.put("id", mailLog.getId());
map.put("mailState", true);
map.put("mailResCode", 1);
map.put("mailResMsg", "发送成功");
map.put("mailCount", null);
LOGGER.info("发送成功");
} catch (Exception e) {
e.printStackTrace();
map.put("id", mailLog.getId());
map.put("mailState", false);
map.put("mailResCode", 0);
map.put("mailResMsg", e.toString());
map.put("mailCount", 1);

LOGGER.info("发送失败");
LOGGER.info(e.toString());
}
mailSender.send(message);
LOGGER.info("邮件已经发送-----");
return map;
}

}-------------
package com.manage.util;

import com.alibaba.fastjson.JSON;
import com.w3china.mingjing3.manage.service.MailLogService;
import com.w3china.mingjing3.model.MailLog;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

import org.slf4j.Logger;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

@Component
@Configurable
@EnableScheduling
public class ScheduledTasks {
private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledTasks.class);
@Autowired
private JavaMailSender mailSender; //自动注入的Bean
@Value("${spring.mail.username}")
private String mailFrom; //读取配置文件中的参数
@Value("${spring.mail.password}")
private String password; //读取配置文件中的参数
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer; //自动注入
@Autowired
private MailLogService mailLogService;

// fixedRate 每次任务结束后会从任务编排表中找下一次该执行的任务,判断是否到时机执行。
// fixedRate 的任务某次执行时间再长也不会造成两次任务实例同时执行,除非用了 @Async 注解。
// fixedDelay 总是前一次任务完成后,延时固定时间然后执行一次任务

@Scheduled(cron = "${scheduled.cron}")
public void reportCurrentByCron() {
LOGGER.info("ScheduledTasks开始定时执行");
List<MailLog> mailLogList = mailLogService.selectByMailState(100); //
Queue<MailLog> queue = new LinkedList<MailLog>();
if (queue.isEmpty()) {
for (int i = 0; i < mailLogList.size(); i++) { // 队列为空的话,就将集合放到队列里
queue.offer(mailLogList.get(i));
}
}
LOGGER.info(JSON.toJSONStringWithDateFormat("queque==" + queue, "yyyy-MM-dd HH:mm:ss"));
Singleton singleton = Singleton.getInstance();
// queue.poll(); //返回第一个元素,并在队列中删除
Map<Object, Object> sendmail = singleton.sendmail(queue.poll(), mailSender, mailFrom, password, freeMarkerConfigurer);

mailLogService.updateMailLogById( // 更新数据库邮件记录表
(Integer) sendmail.get("id"),
(Boolean) sendmail.get("mailState"),
(Integer) sendmail.get("mailResCode"),
(String) sendmail.get("mailResMsg"),
(Integer) sendmail.get("mailCount")
);

}


}

----------------
manage\src\main\resources\templates\mailtemplats\sendQuota.ftl
<html>

<body>
<#--额度发放 邮箱模板-->
<h3>
您好,您提交的${resTypeName!}资源中${refName!}项目的资源申请已通过审核,发放额度${refQuota!}元,请登录系统使用。
</h3>
<#--注意:只给公司业务联系人的邮箱发送-->
</body>

</html>


猜你喜欢

转载自www.cnblogs.com/jwlfpzj/p/9255492.html