Java_发送邮件
- 发送邮件方法
public static boolean sendMail(String receive, String subject, Map map,String templateName)throws GeneralSecurityException {
if (StringUtils.isEmpty(receive)) {
return false;
}
final String from = "XXX@163.com";
final String pass = "XXX";
String host = "smtp-n.global-mail.cn";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(receive));
message.setSubject(subject);
String msg = getMailTextByTemplateName(templateName, map);
message.setContent(msg,"text/html;charset=UTF-8");
Transport.send(message);
return true;
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private static String getMailTextByTemplateName(String templateName, Map<String, String> params){
String mailText = "";
try {
mailText = TextTemplateUtil.mergingByClassPath(templateName, params);
} catch (Exception e) {
e.printStackTrace();
}
return mailText;
}
- 邮件模板
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>邮件提醒</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body style="margin: 0; padding: 0;">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border-collapse: collapse;">
<tr>
<td>
<p style="font-size: 25px;color: #3f3f3f;font-weight: bold;text-align: center;">XXX技术有限公司</p>
</td>
</tr>
<tr>
<td>
<div style="border: #36649d 1px dashed;margin: 30px;padding: 20px">
<label style="font-size: 22px;color: #36649d;font-weight: bold"></label>
<p style="font-size: 16px"> 您好!您申请的项目为:<strong> ${projectName} </strong></p>
<p> 请点击以下链接获取发版文件 </p>
<a href ="${downUrl}">${downUrl}</a>
<p style=" font-size: 16px">( 链接48小时内有效,如无法点击,请复制链接到浏览器访问 )</p>
</div>
</td>
</tr>
</table>
</body>
</html>