需要用到的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>