四、使用 FreeMarker模板
HTML 標簽的字符串拼接是一件很棘手的事。因為在你的大腦中解析HTML標簽並想象它在渲染時會是什么樣子是挺困難的。而將HTML混合在Java代碼中又會使得這個問題更加復雜。
因此 Spring 給出的解決方案是:使用模板生成 HTML 文本,有多種模板方案可供選擇,包括Apache Velocity和freemarker。這里僅介紹 freemarker模板的用法(假設讀者已經熟悉了 freemarker模板並知道如何在 SpringBoot 中使用它們)。
1、在項目templates目錄新建Freemarker模板 — message.ftl
<html>
<head>
<meta charset="UTF-8">
<title>消息通知</title>
</head>
<style type="text/css">
table {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
width: 100%;
border-collapse: collapse;
}
td, th {
font-size: 1em;
border: 1px solid #5B4A42;
padding: 3px 7px 2px 7px;
}
th {
font-size: 1.1em;
text-align: center;
padding-top: 5px;
padding-bottom: 4px;
background-color: #24A9E1;
color: #ffffff;
}
</style>
<body>
<div>
<h2>郵件消息通知</h2>
<table id="customers">
<tr>
<th>MessageCode</th>
<th>MessageStatus</th>
<th>Cause</th>
</tr>
<tr>
<td>${(params.messageCode)!""}</td>
<td>${(params.messageStatus)!""}</td>
<td>${(params.cause)!""}</td>
</tr>
</table>
</div>
</body>
</html>
2、定義發送郵件渲染對象
發送內容為object,通過模板渲染方式接收內容,如下所示
import lombok.Data;
@Data
public class Message {
private String messageCode;
private String messageStatus;
private String cause;
}
3、在application.properties文件中配置mail信息
spring.mail.host=smtp.exmail.qq.com spring.mail.username=123456@qq.cn spring.mail.password=123456 spring.mail.default-encoding=UTF-8
4、編寫EmailService服務接口
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
@Service
@Configuration
public class EmailService {
//郵件的發送者
@Value("${spring.mail.from}")
private String from;
//注入MailSender
@Autowired
private JavaMailSender javaMailSender;
//發送郵件的模板引擎
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
public void sendMessageMail(Object params, String title, String templateName){
try{
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(InternetAddress.parse("zhoucui_test@163.com"));//發送給誰
mimeMessageHelper.setSubject("【" + title + "-" + LocalDate.now() + " " + LocalTime.now().withNano(0) + "】");//郵件標題
Map<String,Object> model = new HashMap<>();
model.put("params",params);
try{
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
try{
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);
mimeMessageHelper.setText(text,true);
javaMailSender.send(mimeMessage);
}catch (TemplateException e){
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
}catch (MessagingException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
}
5、新建controller測試
import com.longteng.diamond.domain.Message;
import com.longteng.diamond.service.EmailService;
import freemarker.template.Configuration;
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.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Controller
public class MimeEmailController {
@Resource
private EmailService emailService;
@RequestMapping(value = "/sendMessage", method = RequestMethod.GET)
@ResponseBody
public String sendMailMessage() {
Message message = new Message();
message.setMessageCode("MissingParameter");
message.setMessageStatus("Failed");
message.setCause("缺少參數,請確認");
emailService.sendMessageMail(message, "測試消息通知", "message.ftl");
return "sendMessage";
}
}
訪問http://localhost:8081/send 出現1測試成功。
