使用JavaMail实现发送模板邮件以及保存到发件箱
需要用到的jar包
1.freemarker-2.3.19.jar
2.javax.mail.jar
3.javax.activation.jar本次测试邮箱是腾讯企业邮箱,其他未经测试。
做这个功能是因为我女朋友每个月都需要手动去发几十个人的考勤、考核邮件,实在是太过重复的做一件很乏味的事情,所以才有了这个程序,不过,界面是使用的控制台,简单一点。
核心代码展示
/** * 发送邮件 * @author hezhao * @Time 2017年3月13日 上午11:25:15 */
public void send() {
System.out.println("正在发送邮件至:::["+to+"] ...");
// 设置邮件服务器
Properties prop = System.getProperties();
prop.put("mail.smtp.host", stmpmailServer);
prop.put("mail.smtp.auth", "true");
prop.put("mail.transport.protocol", this.send);
prop.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.socketFactory.port", this.smtpport);
prop.put("mail.smtp.socketFactory.fallback", "false");
// 使用SSL,企业邮箱必需!
// 开启安全协议
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
// 获取Session对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
// 此访求返回用户和密码的对象
@Override
protected PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication pa = new PasswordAuthentication(username,
password);
return pa;
}
});
// 设置session的调试模式,发布时取消
session.setDebug(true);
try {
// 封装Message对象
Message message = new MimeMessage(session);
// message.setFrom(new InternetAddress(from,from)); //设置发件人
// 设置自定义发件人昵称
String nick_from = "";
try {
nick_from = javax.mail.internet.MimeUtility.encodeText(this.nickname_from);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
message.setFrom(new InternetAddress(nick_from + " <" + from + ">"));
// 设置自定义收件人昵称
String nick_to = "";
try {
nick_to = javax.mail.internet.MimeUtility.encodeText(this.nickname_to);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
message.setRecipient(Message.RecipientType.TO, new InternetAddress(nick_to + " <" + to + ">"));// 设置收件人
message.setSubject(mailSubject);// 设置主题
message.setContent(mailContent, "text/html;charset=utf8");// 设置内容(设置字符集处理乱码问题)
message.setSentDate(new Date());// 设置日期
// 发送
Transport.send(message);
System.out.println("发送成功...");
//保存邮件到发件箱
saveEmailToSentMailFolder(message);
if(mailSubject.contains("考勤")){
FileLog.writeLog(this.nickname_to + " <" + to + ">发送成功");
}else{
FileLog.writeLog(this.nickname_to + " <" + to + ">发送成功");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("发送邮件异常...");
if(mailSubject.contains("考勤")){
FileLog.writeLog(this.nickname_to + " <" + to + ">发送失败");
}else{
FileLog.writeLog(this.nickname_to + " <" + to + ">发送失败");
}
}
}
保存至发件箱
/** * 获取用户的发件箱文件夹 * * @param message * 信息 * @param store * 存储 * @return * @throws IOException * @throws MessagingException */
private Folder getSentMailFolder(Message message, Store store)
throws IOException, MessagingException {
// 准备连接服务器的会话信息
Properties props = new Properties();
props.setProperty("mail.store.protocol", get);
props.setProperty("mail.imap.host", imapmailServer);
props.setProperty("mail.imap.port", "143");
/** QQ邮箱需要建立ssl连接 */
props.setProperty("mail.imap.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.imap.starttls.enable", "true");
props.setProperty("mail.imap.socketFactory.port", imapport);
// 创建Session实例对象
Session session = Session.getInstance(props);
URLName urln = new URLName(get, imapmailServer, 143, null,
username, password);
// 创建IMAP协议的Store对象
store = session.getStore(urln);
store.connect();
// 获得发件箱
Folder folder = store.getFolder("Sent Messages");
// 以读写模式打开发件箱
folder.open(Folder.READ_WRITE);
return folder;
}
/** * 保存邮件到发件箱 * * @param message * 邮件信息 */
private void saveEmailToSentMailFolder(Message message) {
Store store = null;
Folder sentFolder = null;
try {
sentFolder = getSentMailFolder(message, store);
message.setFlag(Flag.SEEN, true); // 设置已读标志
sentFolder.appendMessages(new Message[] { message });
System.out.println("已保存到发件箱...");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 判断发件文件夹是否打开如果打开则将其关闭
if (sentFolder != null && sentFolder.isOpen()) {
try {
sentFolder.close(true);
} catch (MessagingException e) {
e.printStackTrace();
}
}
// 判断邮箱存储是否打开如果打开则将其关闭
if (store != null && store.isConnected()) {
try {
store.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
获取模板内容
/** * 得到模板内容 * @author hezhao * @Time 2017年3月13日 下午1:01:08 * @param fileName * @param map * @return */
public String getMailText(String fileName,Map<String,Object> map){
String htmlText = null;
try {
Template template = config.getTemplate(fileName);
htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
return htmlText;
}
替换模板内容
FreemarkerUtil freemarkerUtil = null;
try {
freemarkerUtil = (FreemarkerUtil) context.getBean("freemarkerUtil");
} catch (Exception e) {
System.out.println("出现异常!!!");
e.printStackTrace();
}
String mailContent = freemarkerUtil.getMailText(fileName, map);
HTML模板(这个还是景洲帮我实现的)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<style> table{ border-collapse:collapse; text-align: center;font-size:12px;} .yellow{ background: #FFFF00;} .blod{ font-weight: bold;} </style>
<body>
<table width="1160" border="1">
<tr>
<td colspan="11" align="center" style="font-size: 22px;">${title}</td>
</tr>
<tr>
<td rowspan="2" class="yellow">序号</td>
<td rowspan="2" class="yellow">部门</td>
<td rowspan="2" class="yellow">姓名</td>
<td rowspan="2" class="yellow">入职时间</td>
<td colspan="5" class="blod" style="font-size: 14px;">考勤结果汇总</td>
<td> </td>
<td rowspan="2" >备注</td>
</tr>
<tr>
<td>正常出勤</td>
<td>请假小时</td>
<td>迟到分钟</td>
<td>迟到扣款</td>
<td>旷工天数</td>
<td>休年假天数</td>
</tr>
<tr>
<td>${no}</td>
<td>${dept}</td>
<td>${name}</td>
<td>${intotime}</td>
<td class="yellow blod">${workday}</td>
<td class="blod">${outhour}</td>
<td class="blod">${deletemin}</td>
<td class="blod">${deletemoney}</td>
<td class="blod">${kg}</td>
<td class="blod">${year}</td>
<td>${remark}</td>
</tr>
</table>
<div>
<br />
</div>
<hr style="width: 210px; height: 1px;" color="#b5c4df" size="1" align="left">
<div style="font-size: 14px;font-family: 'lucida Grande', Verdana;">
<span>${bottom}</span>
</div>
</body>
</html>
原文作者:窗边冷月光
原文地址: https://blog.csdn.net/sinat_27403673/article/details/77370209
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/sinat_27403673/article/details/77370209
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
相关文章