获取邮件模板
public String getMailContent(String name, String tel) throws IOException {
StringWriter stringWriter = new StringWriter();
// velocity引擎
VelocityEngine velocityEngine = new VelocityEngine();
// 设置文件路径属性
Properties properties = new Properties();
String dir = this.getClass().getResource("/").getPath();
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, dir + "static/template/");
// 引擎初始化属性配置
velocityEngine.init(properties);
// 加载指定模版
Template template = velocityEngine.getTemplate("userInfo.vm", "utf-8");
// 填充模板内容
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("name", name);
velocityContext.put("tel", tel);
// 写到模板
template.merge(velocityContext, stringWriter);
return stringWriter.toString();
}
发送邮件
public static void doSend(String name,String tel,String subject)
throws UnsupportedEncodingException, MessagingException {
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
senderImpl.setHost(host);
senderImpl.setUsername(username);
senderImpl.setPassword(password);
MimeMessage mailMessage = senderImpl.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mailMessage, true, "utf-8");
message.setFrom(new InternetAddress(MimeUtility.encodeText(from, "utf-8", null)
+ " <" + fromAddress + ">"));
message.setTo(to);
message.setSubject(subject);
message.setText(getMailContent(name,tel), true);
Properties prop = new Properties();
prop.put("mail.smtp.auth", "false"); // 此smtp不需要认证
prop.put("mail.smtp.port", port);
prop.put("mail.smtp.timeout", 60000); // 超时
senderImpl.setJavaMailProperties(prop);
senderImpl.send(mailMessage);
}
在模板文件中使用$符获取:
<tr>
<td style="padding: 70px 0 0 185px">
<span style="font-size:14px">Hi,$name:</span>
</td>
</tr>
<tr>
<td style="padding: 12px 0 70px 185px">
<span style="font-size:14px">$tel</span>
</td>
</tr>