java利用模板发送邮件_使用JavaMail实现发送模板邮件以及保存到发件箱
需要用到的jar包
1.freemarker-2.3.19.jar
2.javax.mail.jar
3.javax.activation.jar
本次測(cè)試郵箱是騰訊企業(yè)郵箱,其他未經(jīng)測(cè)試。
做這個(gè)功能是因?yàn)槲遗笥衙總€(gè)月都需要手動(dòng)去發(fā)幾十個(gè)人的考勤、考核郵件,實(shí)在是太過(guò)重復(fù)的做一件很乏味的事情,所以才有了這個(gè)程序,不過(guò),界面是使用的控制臺(tái),簡(jiǎn)單一點(diǎn)。
核心代碼展示
/**
* 發(fā)送郵件
* @author hezhao
* @Time 2017年3月13日 上午11:25:15
*/
public void send() {
System.out.println("正在發(fā)送郵件至:::["+to+"] ...");
// 設(shè)置郵件服務(wù)器
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,企業(yè)郵箱必需!
// 開啟安全協(xié)議
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對(duì)象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
// 此訪求返回用戶和密碼的對(duì)象
@Override
protected PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication pa = new PasswordAuthentication(username,
password);
return pa;
}
});
// 設(shè)置session的調(diào)試模式,發(fā)布時(shí)取消
session.setDebug(true);
try {
// 封裝Message對(duì)象
Message message = new MimeMessage(session);
// message.setFrom(new InternetAddress(from,from)); //設(shè)置發(fā)件人
// 設(shè)置自定義發(fā)件人昵稱
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 + " "));
// 設(shè)置自定義收件人昵稱
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 + " "));// 設(shè)置收件人
message.setSubject(mailSubject);// 設(shè)置主題
message.setContent(mailContent, "text/html;charset=utf8");// 設(shè)置內(nèi)容(設(shè)置字符集處理亂碼問(wèn)題)
message.setSentDate(new Date());// 設(shè)置日期
// 發(fā)送
Transport.send(message);
System.out.println("發(fā)送成功...");
//保存郵件到發(fā)件箱
saveEmailToSentMailFolder(message);
if(mailSubject.contains("考勤")){
FileLog.writeLog(this.nickname_to + " 發(fā)送成功");
}else{
FileLog.writeLog(this.nickname_to + " 發(fā)送成功");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("發(fā)送郵件異常...");
if(mailSubject.contains("考勤")){
FileLog.writeLog(this.nickname_to + " 發(fā)送失敗");
}else{
FileLog.writeLog(this.nickname_to + " 發(fā)送失敗");
}
}
}
保存至發(fā)件箱
/**
* 獲取用戶的發(fā)件箱文件夾
*
* @param message
* 信息
* @param store
* 存儲(chǔ)
* @return
* @throws IOException
* @throws MessagingException
*/
private Folder getSentMailFolder(Message message, Store store)
throws IOException, MessagingException {
// 準(zhǔn)備連接服務(wù)器的會(huì)話信息
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);
// 創(chuàng)建Session實(shí)例對(duì)象
Session session = Session.getInstance(props);
URLName urln = new URLName(get, imapmailServer, 143, null,
username, password);
// 創(chuàng)建IMAP協(xié)議的Store對(duì)象
store = session.getStore(urln);
store.connect();
// 獲得發(fā)件箱
Folder folder = store.getFolder("Sent Messages");
// 以讀寫模式打開發(fā)件箱
folder.open(Folder.READ_WRITE);
return folder;
}
/**
* 保存郵件到發(fā)件箱
*
* @param message
* 郵件信息
*/
private void saveEmailToSentMailFolder(Message message) {
Store store = null;
Folder sentFolder = null;
try {
sentFolder = getSentMailFolder(message, store);
message.setFlag(Flag.SEEN, true); // 設(shè)置已讀標(biāo)志
sentFolder.appendMessages(new Message[] { message });
System.out.println("已保存到發(fā)件箱...");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 判斷發(fā)件文件夾是否打開如果打開則將其關(guān)閉
if (sentFolder != null && sentFolder.isOpen()) {
try {
sentFolder.close(true);
} catch (MessagingException e) {
e.printStackTrace();
}
}
// 判斷郵箱存儲(chǔ)是否打開如果打開則將其關(guān)閉
if (store != null && store.isConnected()) {
try {
store.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
獲取模板內(nèi)容
/**
* 得到模板內(nèi)容
* @author hezhao
* @Time 2017年3月13日 下午1:01:08
* @param fileName
* @param map
* @return
*/
public String getMailText(String fileName,Map 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;
}
替換模板內(nèi)容
FreemarkerUtil freemarkerUtil = null;
try {
freemarkerUtil = (FreemarkerUtil) context.getBean("freemarkerUtil");
} catch (Exception e) {
System.out.println("出現(xiàn)異常!!!");
e.printStackTrace();
}
String mailContent = freemarkerUtil.getMailText(fileName, map);
HTML模板(這個(gè)還是景洲幫我實(shí)現(xiàn)的)
table{border-collapse:collapse; text-align: center;font-size:12px;}
.yellow{background: #FFFF00;}
.blod{font-weight: bold;}
| ${title} | ||||||||||
| 序號(hào) | 部門 | 姓名 | 入職時(shí)間 | 考勤結(jié)果匯總 | 備注 | |||||
| 正常出勤 | 請(qǐng)假小時(shí) | 遲到分鐘 | 遲到扣款 | 曠工天數(shù) | 休年假天數(shù) | |||||
| ${no} | ${dept} | ${name} | ${intotime} | ${workday} | ${outhour} | ${deletemin} | ${deletemoney} | ${kg} | ${year} | ${remark} |
${bottom}
總結(jié)
以上是生活随笔為你收集整理的java利用模板发送邮件_使用JavaMail实现发送模板邮件以及保存到发件箱的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java 上传文件编码_(java)有什
- 下一篇: java外键实体类_java – 在Em