最近在項目中開發中須要用到發送郵件功能,當後臺定時任務處理完畢後通知調用者。Java Mail API使用比較麻煩,因此這裏採用的是Apache Commons Email,官網地址:http://commons.apache.org/proper/commons-email/,Commons Email API比較簡潔高效,學習起來也很快。html
一、發送簡單文本郵件java
Email email = new SimpleEmail(); email.setHostName("smtp.googlemail.com"); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator("username", "password")); email.setSSLOnConnect(true); email.setFrom("user@gmail.com"); email.setSubject("TestMail"); email.setMsg("This is a test mail ... :-)"); email.addTo("foo@bar.com"); email.send();
二、發送帶附件的郵件apache
// Create the attachment EmailAttachment attachment = new EmailAttachment(); attachment.setPath("mypictures/john.jpg"); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("Picture of John"); attachment.setName("John"); // Create the email message MultiPartEmail email = new MultiPartEmail(); email.setHostName("mail.myserver.com"); email.addTo("jdoe@somewhere.org", "John Doe"); email.setFrom("me@apache.org", "Me"); email.setSubject("The picture"); email.setMsg("Here is the picture you wanted"); // add the attachment email.attach(attachment); // send the email email.send();
另外還能夠經過任意的連接來將網絡上的文件添加到附件中,例如:編程
// Create the attachment EmailAttachment attachment = new EmailAttachment(); attachment.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif")); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("Apache logo"); attachment.setName("Apache logo"); // Create the email message MultiPartEmail email = new MultiPartEmail(); email.setHostName("mail.myserver.com"); email.addTo("jdoe@somewhere.org", "John Doe"); email.setFrom("me@apache.org", "Me"); email.setSubject("The logo"); email.setMsg("Here is Apache's logo"); // add the attachment email.attach(attachment); // send the email email.send();
三、發送HTML格式的郵件網絡
// Create the email message HtmlEmail email = new HtmlEmail(); email.setHostName("mail.myserver.com"); email.addTo("jdoe@somewhere.org", "John Doe"); email.setFrom("me@apache.org", "Me"); email.setSubject("Test email with inline image"); // embed the image and get the content id URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif"); String cid = email.embed(url, "Apache logo"); // set the html message email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>"); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // send the email email.send();
四、發送帶圖片的HTML格式郵件ide
// load your HTML email template String htmlEmailTemplate = .... // define you base URL to resolve relative resource locations URL url = new URL("http://www.apache.org"); // create the email message HtmlEmail email = new ImageHtmlEmail(); email.setDataSourceResolver(new DataSourceResolverImpl(url)); email.setHostName("mail.myserver.com"); email.addTo("jdoe@somewhere.org", "John Doe"); email.setFrom("me@apache.org", "Me"); email.setSubject("Test email with inline image"); // set the html message email.setHtmlMsg(htmlEmailTemplate); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // send the email email.send();
另外,在使用過程當中發現Email.addTo一次只能添加一個聯繫人,若是想發送給多我的的話,須要使用for循環嵌套來實現,如下是一個簡單的例子:單元測試
public static void main(String[] args){ String mailList = "abc@163.com;tt@qq.com"; String[] list = mailList.split(";"); for(int i=0;list!=null && i<list.length;i++){ //嵌套調用 sendEmail(list[i]); } } public static void sendEmail(String target) { try{ Email email = new SimpleEmail(); email.setHostName("smtp.163.com"); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator("abc@163.com","abc")); email.setSSLOnConnect(true); email.setFrom("abc@163.com"); email.addTo(target); email.setSubject("Test Mail"); email.setMsg("This is a test mail"); email.send(); }catch (Exception e){ e.printStackTrace(); } }
基於構造着模式的apache email send學習
package com.haiziwang.platform.tool.core; import com.haiziwang.platform.tool.dependency.EmailException; import com.haiziwang.platform.tool.dependency.HtmlEmail; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; /** * Created by wangzhongbao on 2016/10/21. */ public class EmailHelper { private static final Log logger = LogFactory.getLog(EmailHelper.class); //郵箱host private String hostName; //發送方帳號 private String authAccount; //發送方密碼 private String authPwd; //郵件主題 private String subject; //郵件正文html private String mailBody; //郵件正文text private String textMsg; //接收人列表 private List<String> receivers = new ArrayList<String>(); //抄送人列表 private List<String> ccReceivers = new ArrayList<String>(); //密送人列表 private List<String> bccReceivers = new ArrayList<String>(); private EmailHelper(Builder b) { this.hostName = b.hostName; this.authAccount = b.authAccount; this.authPwd = b.authPwd; this.subject = b.subject; this.mailBody = b.mailBody; this.textMsg = b.textMsg; this.receivers = b.receivers; this.ccReceivers = b.ccReceivers; this.bccReceivers = b.bccReceivers; } public boolean send() { boolean success = true; try { sendByNative(); } catch (Exception e) { e.printStackTrace(); logger.error("mail send fail,errmsg:"+e.toString()); success = false; } return success; } /** * 原始發送,若是有異常會直接往上拋出 * @throws EmailException */ public void sendByNative() throws EmailException { HtmlEmail email = new HtmlEmail(); email.setCharset("UTF-8"); email.setFrom(authAccount, authAccount); email.setAuthentication(authAccount, authPwd); email.setHostName((hostName!=null && !"".equals(hostName))?hostName:"smtp.exmail.qq.com"); for(String r:receivers){ email.addTo(r, ""); } for(String r:ccReceivers){ email.addCc(r, ""); } for(String r:bccReceivers){ email.addBcc(r, ""); } email.setSubject(subject); if(null!=mailBody && !"".equals(mailBody)){ email.setContent(mailBody, "text/html;charset=utf-8"); }else{ email.setTextMsg(textMsg); } email.send(); } //構造着模式,fluence編程風格 public static class Builder{ private String hostName; private String authAccount; private String authPwd; private String subject; private String mailBody; private String textMsg; private List<String> receivers = new ArrayList<String>(); private List<String> ccReceivers = new ArrayList<String>(); private List<String> bccReceivers = new ArrayList<String>(); public Builder hostName(String hostName) { this.hostName = hostName; return this; } public Builder authAccount(String authAccount){ this.authAccount = authAccount; return this; } public Builder authPwd(String authPwd){ this.authPwd = authPwd; return this; } public Builder authentication(String authAccount,String authPwd){ this.authAccount = authAccount; this.authPwd = authPwd; return this; } public Builder subject(String subject){ this.subject = subject; return this; } public Builder mailBody(String mailBody){ this.mailBody = mailBody; return this; } public Builder textMsg(String textMsg){ this.textMsg = textMsg; return this; } public Builder receivers(List<String> receivers){ this.receivers.addAll(receivers); return this; } public Builder addReceiver(String receiver){ if(receiver!=null && !"".equals(receiver)){ String[] receiverArr = receiver.split(","); for(String r:receiverArr){ receivers.add(r); } } return this; } public Builder ccReceivers(List<String> ccReceivers){ this.ccReceivers.addAll(ccReceivers); return this; } public Builder addCcReceiver(String ccReceiver){ if(ccReceiver!=null && !"".equals(ccReceiver)){ String[] ccReceiverArr = ccReceiver.split(","); for(String r:ccReceiverArr){ ccReceivers.add(r); } } return this; } public Builder bccReceivers(List<String> bccReceivers){ this.bccReceivers.addAll(bccReceivers); return this; } public Builder addBccReceiver(String bccReceiver){ if(bccReceiver!=null && !"".equals(bccReceiver)){ String[] bccReceiverArr = bccReceiver.split(","); for(String r:bccReceiverArr){ bccReceivers.add(r); } } return this; } public EmailHelper builder(){ return new EmailHelper(this); } } } public class Sample { /** * TODO未作junit測試,直接寫了一個main作單元測試 * * @param args */ public static void main(String[] args) throws EmailException, MalformedURLException { new EmailHelper.Builder().authentication("wang_ffag@haiziwang.com", "111111") .subject("天氣預報").mailBody("<font style='color:red;'>天氣不錯哦</font>").addReceiver("zhongbao.wang@haiziwang.com").builder().send(); } }