本文主要是记录一下在开发过程中使用到的技术点,方便以后回顾,也希望能帮到有需要的朋友。
使用的freemarker版本
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker-gae</artifactId>
<version>2.3.23</version>
</dependency>
创建freemarker工具类
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
/**
* @author cn.yantz@qq.com
* @version 1.0
* @since 2021/1/21 14:48
*/
public class FreemarkerGeneratorUtil {
private Template createTemplate(String templateName) throws IOException {
FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(new File(Thread.currentThread().getContextClassLoader().getResource("templates/").getPath()));
Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
configuration.setTemplateLoader(fileTemplateLoader);
return configuration.getTemplate(templateName, "UTF-8");
}
/**
* Freemarker生成HTML字符串
*
* @param templateName 模板名称.ftl
* @param templateData 模板数据
* @return HTML字符串
* @throws IOException IO异常
* @throws TemplateException 模板读取异常
*/
public String generateToString(String templateName, Map<String, Object> templateData) throws IOException, TemplateException {
StringWriter stringWriter = new StringWriter();
Template template = createTemplate(templateName);
template.process(templateData, stringWriter);
stringWriter.flush();
return stringWriter.toString();
}
private static FreemarkerGeneratorUtil freemarkerGeneratorUtil = null;
public static synchronized FreemarkerGeneratorUtil getInstance() {
if (freemarkerGeneratorUtil == null) {
synchronized (FreemarkerGeneratorUtil.class) {
if (freemarkerGeneratorUtil == null) {
freemarkerGeneratorUtil = new FreemarkerGeneratorUtil();
}
}
}
return freemarkerGeneratorUtil;
}
}
Freemarker调用代码
拼接模板数据,调用帮助类生成字符串
// 创建模板数据
Map<String, Object> templateData = new HashMap<>(16);
templateData.put("orderNo", getClientOrderDetailPageUrl(orderNo));
templateData.put(LINK_URL_KEY, getClientOrderDetailPageUrl(orderNo));
// 生成HTML字符串
String pendingConfirmExpenses = FreemarkerGeneratorUtil.getInstance().generateToString("pendingConfirmExpenses.ftl", templateData);
模板文件
- 文件放的位置,通过
Thread.currentThread().getContextClassLoader().getResource("templates/").getPath()获取
- 文件语法:http://freemarker.foofun.cn/
邮件配置
- 邮件配置与Springmvc集成
<!-- 发送邮件 -->
<bean id="javaMailSender"
class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.smtp.host}"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="username" value="${mail.service.username}"/>
<property name="password" value="${mail.service.password}"/>
<property name="port" value="465"/>
<property name="javaMailProperties">
<props>
<!-- 设置认证开关 -->
<prop key="mail.smtp.auth">true</prop>
<!-- 启动调试开关 -->
<prop key="mail.debug">false</prop>
<!-- 设置发送延时 -->
<prop key="mail.smtp.timeout">0</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
<prop key="mail.smtp.socketFactory.port">465</prop>
</props>
</property>
</bean>
- 新建邮件发送服务
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author cn.yantz@qq.com
* @date 2020/7/8 20:35
*/
@Service
public class EmailSendUtilsServiceImpl implements EmailSendUtilsService {
private static final String SYMBOL_SPLIT = ";";
private static final String SYMBOL_COMMA = ",";
private static final Logger LOGGER = LoggerFactory.getLogger(EmailSendUtilsServiceImpl.class);
@Autowired
private JavaMailSender javaMailSender;
private String getMailPicturePath() {
try {
String path = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
path = path + "email/mail.png";
LOGGER.info(">>>获取当前邮件LOGO地址:{}", path);
return path;
} catch (Exception e) {
LOGGER.error("获取本地邮件LOGO地址异常", e);
}
return AppProp.MAIL_STATIC_BASE_FOLDER + "pdf/mail.png";
}
/**
* 同步发送邮件
*
* @param mailModel 邮件数据模型
*/
@Override
public void sendMail(GlobalMailModel mailModel) throws MessagingException {
String mailModelString = mailModel.toString();
LOGGER.info(">>> Mail Info {}", mailModelString);
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true, "UTF-8");
InternetAddress[] toAddress = getAddress(mailModel.getTo());
LOGGER.info(">>> toAddress : {}", (Object) toAddress);
mimeMessageHelper.setTo(toAddress);
mimeMessageHelper.setFrom(mailModel.getFrom());
String cc = mailModel.getCc();
if (StringUtils.isNotBlank(cc)) {
LOGGER.info(">>> ccAddress : {}", (Object) getAddress(cc));
mimeMessageHelper.setCc(getAddress(cc));
}
mimeMessageHelper.setSubject(mailModel.getSubject());
mimeMessageHelper.setText(mailModel.getContents(), mailModel.getHtmlBodyFlag());
FileSystemResource res = new FileSystemResource(new File(getMailPicturePath()));
mimeMessageHelper.addInline("myImg", res);
javaMailSender.send(message);
LOGGER.info(">>> Send Email Success >>>");
}
/**
* 处理多发件人问题
*
* @param addr 邮件地址
* @return InternetAddress[]
* @throws AddressException
*/
private InternetAddress[] getAddress(String addr) throws AddressException {
if (addr.contains(SYMBOL_COMMA) || addr.contains(SYMBOL_SPLIT)) {
addr = addr.replace("\n", "").replace("\r", "").replace(SYMBOL_SPLIT, SYMBOL_COMMA);
String[] median = addr.split(SYMBOL_COMMA);
//不能使用string类型的类型,这样只能发送一个收件人
List<InternetAddress> list = new ArrayList<>(10);
for (int i = 0; i < median.length; i++) {
list.add(new InternetAddress(median[i]));
}
return list.toArray(new InternetAddress[0]);
} else {
InternetAddress ccAddr = new InternetAddress(addr);
InternetAddress[] addresses = new InternetAddress[1];
addresses[0] = ccAddr;
return addresses;
}
}
}
文件中
FileSystemResource res = new FileSystemResource(new File(getMailPicturePath()));
mimeMessageHelper.addInline("myImg", res);
处理邮件中显示图片Logo,ftl文件中如下
GlobalMailModel
邮件发送调用
emailSendUtilsService.sendMail(mailModel);
至此,通过freemarker生成邮件内容并发送完成~!!