jar
<!--Email相關開始-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--Email相關結束-->
Mail郵件對象
public class Mail implements Serializable {
private static final long serialVersionUID = 1L;
//接收方郵件
private String email;
//主題
private String subject;
//模板
private String template;
// 自定義參數
private Map<String, Object> params;
}
實現
@Component
public class MailSendService {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
//發件人
@Value("${spring.mail.username}")
private String fromMail;
//主題名稱
//@Value("${mail.subjectName}")
//private String subjectName;
/**
* 根據模板名 獲取郵件內容
*/
private String getMailTextByTemplateName(String templateName, Map<String, Object> params) throws IOException, TemplateException {
try {
String mailText = "";
//通過指定模板名獲取FreeMarker模板實例
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
mailText = FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
return mailText;
}catch (TemplateNotFoundException e) {
//若找不到指定模板則使用默認模板
templateName="busi_situation.ftl";
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
return FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
}
}
public Result sendWithHTMLTemplate(Mail mail) {
try {
String email = mail.getEmail();
if (StringUtil.isBlank(email)) {
return ResultUtil.error("郵箱email不能為空!");
}
if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
return ResultUtil.error("郵箱email格式不正確!");
}
//發件人昵稱
String nick = MimeUtility.encodeText(fromMail);
//發件人
InternetAddress from = new InternetAddress(nick + "<" + fromMail + ">");
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
//收件人
mimeMessageHelper.setTo(email);
mimeMessageHelper.setFrom(from);
//圖片
String fileUrl = this.getClass().getClassLoader().getResource("public/static/img/mail/logo.png").getPath();
FileSystemResource img1 = new FileSystemResource(new File(fileUrl));
mimeMessageHelper.addInline("logo1", img1);
FileSystemResource img2 = new FileSystemResource(new File(fileUrl));
mimeMessageHelper.addInline("logo2", img2);
//附件
String filePath= this.getClass().getClassLoader().getResource("public/static/img/mail/text.txt").getPath();
FileSystemResource file=new FileSystemResource(new File(filePath));
String fileName=filePath.substring(filePath.lastIndexOf(File.separator));
//添加多個附件可以使用多條
mimeMessageHelper.addAttachment(fileName,file);
Map<String, Object> params = mail.getParams();
mail.setParams(params);
mimeMessageHelper.setSubject(subjectName);
// 使用模板生成html郵件內容
String result = getMailTextByTemplateName(mail.getTemplate(), mail.getParams());
mimeMessageHelper.setText(result, true);
javaMailSender.send(mimeMessage);
return ResultUtil.success("郵件發送成功");
} catch (Exception e) {
logger.error("發送郵件失敗" + e.getMessage());
return ResultUtil.error("發送郵件時發生異常:" + e.getMessage());
}
}
}
郵件服務器SSL安全證書認證
public class MailSocketFactory extends SSLSocketFactory {
private SSLSocketFactory factory;
public MailSocketFactory() {
try {
// 獲取一個SSLContext實例
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[]{new MailTrustManager()}, null);
//從上述SSLContext對象中得到SSLSocketFactory對象
factory = sslcontext.getSocketFactory();
} catch (Exception ex) {
// ignore
}
}
public static SocketFactory getDefault() {
return new MailSocketFactory();
}
@Override
public Socket createSocket() throws IOException {
return factory.createSocket();
}
@Override
public Socket createSocket(Socket socket, String s, int i, boolean flag) throws IOException {
return factory.createSocket(socket, s, i, flag);
}
@Override
public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr1, int j) throws IOException {
return factory.createSocket(inaddr, i, inaddr1, j);
}
@Override
public Socket createSocket(InetAddress inaddr, int i) throws IOException {
return factory.createSocket(inaddr, i);
}
@Override
public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException {
return factory.createSocket(s, i, inaddr, j);
}
@Override
public Socket createSocket(String s, int i) throws IOException {
return factory.createSocket(s, i);
}
@Override
public String[] getDefaultCipherSuites() {
return factory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return factory.getSupportedCipherSuites();
}
}
證書信任管理器
public class MailTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
//返回受信任的X509證書數組。
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
配置文件
spring.mail.default-encoding=UTF-8
spring.mail.host=mail.x'x'x.x'x'x.xxx
spring.mail.username=x'x'xxxxxxx
spring.mail.password=x'x'xxxx
# 協議
spring.mail.protocol=smtp
spring.mail.port=x'x'x
spring.mail.properties.mail.smtp.auth=truexxx
spring.mail.properties.mail.smtp.starttls.enable=false
spring.mail.properties.mail.smtp.starttls.required=false
spring.mail.properties.mail.smtp.socketFactory.port=x'x'x
## SSL認證工廠
spring.mail.properties.mail.smtp.socketFactory.class=com.xxx.msg.impl.MailSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback=false
freemarrker模板
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>截至郵件發送時間</title>
<meta http-equiv="keywords" content="data">
<meta http-equiv="description" content="data">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body >
<div class="content">
<div class="main">
<div class="status">
<div class="status-top">
<div class="logo flex-align"> <img src="cid:logo1" alt="" width="35" height="35"><span>${data.name}</span></div>
<div class="status-content">
<div class="status-content-top flex-align flex-justify-center">
<h2>xxx</h2>
<span>
<i></i>
<i></i>
<i></i>
</span>
</div>
<div class="status-content-c flex-r flex-jusify-space-bettween">
<div class="normal flex-c flex-align flex-justify-center">
<p>${data.sum}</p>
<span>xxx</span>
</div>
<div class="success flex-c flex-align flex-justify-center">
<p>${data.sum}</p>
<span>xxx</span>
</div>
</div>
</div>
</div>
<div class="dataDec">
<div>
<h4 class="flex-align">xxx</h4>
<table>
<thead>
<tr>
<th width="180" align="left">名稱</th>
</tr>
</thead>
<tbody>
<#list data as item>
<tr>
<#list item?keys as itemKey>
<#if itemKey="name" >
<td align="left">${item[itemKey]}</td>
</#if>
</#list>
</tr>
</#list>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>