本文章內容——通過java語言以最簡單的方式實現郵件發送功能。
文章目的是能夠引導讀者成功發送郵件,將在幫助理解郵箱發送的同時,附上最簡單的實例代碼,並盡可能簡潔明了。
首先了解發送郵件之原理(不需要了解的可以跳過):
首先介紹SMTP(Simple Mail Transfer Protocol)即簡單郵件傳輸協議,它是一組由源地址向目標地址傳送郵件的規則,由它來控制信件的中轉方式。
SMTP協議屬於TCP/IP協議簇,它幫助每台計算機在發送或中轉信件時找到下一個目的地。
SMTP服務器即是遵循SMTP協議的郵件發送服務器,用來發送或中轉電子郵件。
更加簡單的理解方式,可以這樣總結 —— SMTP協議:地址獲取者,尋找者。 SMTP服務器:郵件轉發者。 以上構成對JAVA何以實現郵件發送之最基礎解答。
圖:發送SMTP郵件的基本原理
了解了SMTP服務器之后,我們要完成郵件發送的功能,只需要完成三個步驟——
1:完成開發准備
2:配置SMTP服務器
3:在JAVA中配置發件人的信息與收件人信息
1:完成開發准備
需要發件與收件郵箱 並開啟SMTP服務 下圖以網易163郵箱舉例:
重點注意:第一次設置SMTP需要設置客戶端授權密碼(和郵箱登錄密碼不同),此后代碼中的發件人密碼以客戶端為准。
需要導入一個JAR包(javax.mail.jar) 附上Jar包下載地址:http://www.oracle.com/technetwork/java/javamail/index-138643.html
2:配置SMTP服務器
為方便調用,首先創造一個郵件發送工具類。
郵件發送工具MailUtil包含兩個方法,第一個方法用來完成SMTP服務器配置及郵件發送,第二個方法用來生成一封郵件實例。
代碼已作了詳細的注釋,此處不作過多解釋。
import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.*; import java.util.Date; import java.util.Properties; /** * @創建人 Levi * @功能描述 郵件發送工具 * @創建時間 2018-07-18 14:08:08 */ public class MailUtil { /** * SMTP服務器配置及郵件發送 * @throws Exception */ public void sendMail(MailConfig mc) throws Exception { try{ // 連接郵件服務器的參數配置 Properties props = new Properties(); // 設置用戶的認證方式 props.setProperty("mail.smtp.auth", "true"); // 設置傳輸協議(JavaMail規范要求) props.setProperty("mail.transport.protocol","smtp"); // 設置發件人的SMTP服務器地址 props.setProperty("mail.smtp.host", "smtp.163.com"); // 設置SMTP服務器端口 一般填寫:25 props.setProperty("mail.smtp.port","25"); // 創建定義整個應用程序所需的環境信息的 Session 對象 Session session = Session.getInstance(props); // 設置調試信息在控制台打印出來 session.setDebug(true); // 創建郵件的實例對象 Message msg = getMimeMessage(session,mc); // 根據session對象獲取郵件傳輸對象Transport Transport transport = session.getTransport(); // 設置發件人的賬戶名和密碼 if(mc.getSenderAccount()==null || mc.getSenderAccount().isEmpty()){ throw new Exception("發件人賬戶為空"); } if(mc.getSenderPassword()==null || mc.getSenderPassword().isEmpty()){ throw new Exception("發件人密碼為空"); } transport.connect(mc.getSenderAccount(), mc.getSenderPassword()); // 發送郵件,並發送到所有收件人地址,message.getAllRecipients() 獲取到的是在創建郵件對象時添加的所有收件人, 抄送人, 密送人 transport.sendMessage(msg,msg.getAllRecipients()); // 關閉郵件連接 transport.close(); }catch(Exception e){ e.printStackTrace(); } } /** * 獲取郵件的實例對象 * @param session * @return MimeMessage * @throws MessagingException * @throws AddressException */ private MimeMessage getMimeMessage(Session session,MailConfig mc) throws Exception{ // 創建一封郵件的實例對象 MimeMessage msg = new MimeMessage(session); // 設置發件人地址 if (mc.getSenderAddress()!=null && !mc.getSenderAddress().isEmpty()){ msg.setFrom(new InternetAddress(mc.getSenderAddress())); }else{ throw new Exception("發件人地址為空"); } /** * 設置收件人地址(可以增加多個收件人、抄送、密送),即下面這一行代碼書寫多行 * MimeMessage.RecipientType.TO:發送 * MimeMessage.RecipientType.CC:抄送 * MimeMessage.RecipientType.BCC:密送 */ if (mc.getRecipientAddresses()!=null && !mc.getRecipientAddresses().isEmpty()){ InternetAddress[] recipients = new InternetAddress().parse(mc.getRecipientAddresses()); msg.setRecipients(MimeMessage.RecipientType.TO, recipients); }else{ throw new Exception("收件人地址為空"); } if (mc.getCopyToAddresses()!=null && !mc.getCopyToAddresses().isEmpty()){ InternetAddress[] copyTos = new InternetAddress().parse(mc.getCopyToAddresses()); msg.setRecipients(MimeMessage.RecipientType.CC,copyTos); } // 設置郵件主題 if (mc.getSubject()!=null && !mc.getSubject().isEmpty()){ msg.setSubject(mc.getSubject(),"UTF-8"); }else{ throw new Exception("郵件主題為空"); } //設置郵件正文 // 設置(文本+圖片)和 附件 的關系(合成一個大的混合"節點" / Multipart ) MimeMultipart mm = new MimeMultipart(); // 混合關系 mm.setSubType("mixed"); // 創建附件"節點" MimeBodyPart body = new MimeBodyPart(); if (mc.getContent()!=null && !mc.getContent().isEmpty()){ body.setContent(mc.getContent(), "text/html;charset=UTF-8"); }else{ throw new Exception("郵件內容為空"); } mm.addBodyPart(body); // 如果有多個附件,可以創建多個多次添加 if(mc.getAttachmentPaths()!=null && mc.getAttachmentPaths().length>0){ for (String attachmentPath: mc.getAttachmentPaths()) { // 創建附件"節點" MimeBodyPart attachment = new MimeBodyPart(); // 讀取本地文件 DataHandler dh = new DataHandler(new FileDataSource(attachmentPath)); // 將附件數據添加到"節點" attachment.setDataHandler(dh); // 設置附件的文件名(需要編碼) attachment.setFileName(MimeUtility.encodeText(dh.getName())); mm.addBodyPart(attachment); // 如果有多個附件,可以創建多個多次添加 } } // 設置整個郵件的關系(將最終的混合"節點"作為郵件的內容添加到郵件對象) msg.setContent(mm); // 設置郵件的發送時間,默認立即發送 msg.setSentDate(new Date()); msg.saveChanges(); return msg; } }
3:在JAVA中配置郵件內容
配置完SMTP服務器內容后,我們將配置郵件內容(包括發件人,收件人信息,郵件主題,內容等)
首先構建郵件實體類
public class MailConfig { //發件人地址 private String senderAddress; //發件人賬戶名 private String senderAccount; //發件人賬戶密碼 private String senderPassword; /** * 收件人地址,多個以","隔開 */ private String recipientAddresses; /** * 抄送人地址,多個以","隔開 */ private String copyToAddresses; //郵件標題 private String subject; //郵件正文 private String content; //附件路徑 private String[] attachmentPaths; public String getSenderAddress() { return senderAddress; } public void setSenderAddress(String senderAddress) { this.senderAddress = senderAddress; } public String getSenderAccount() { return senderAccount; } public void setSenderAccount(String senderAccount) { this.senderAccount = senderAccount; } public String getSenderPassword() { return senderPassword; } public void setSenderPassword(String senderPassword) { this.senderPassword = senderPassword; } public String getRecipientAddresses() { return recipientAddresses; } public void setRecipientAddresses(String recipientAddresses) { this.recipientAddresses = recipientAddresses; } public String getCopyToAddresses() { return copyToAddresses; } public void setCopyToAddresses(String copyToAddresses) { this.copyToAddresses = copyToAddresses; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String[] getAttachmentPaths() { return attachmentPaths; } public void setAttachmentPaths(String[] attachmentPaths) { this.attachmentPaths = attachmentPaths; } }
然后,配置郵件的具體內容 並調用郵件發送工具類。
public class MailSend {
//采用單例以提供持久可用的工具類對象 static MailUtil mu = new MailUtil(); public static void main(String arg[]){ try { MailConfig mc = new MailConfig(); //設置發件人地址 mc.setSenderAddress("sender@163.com"); //設置發件人賬戶名 mc.setSenderAccount("sender@163.com"); //設置發件人密碼(備注:密碼需要用郵箱SMTP客戶端授權密碼,而非登錄密碼,此處需注意) mc.setSenderPassword("mypassword"); //設置郵件主題 mc.setSubject("郵件發送測試"); //設置收件人地址,多個地址可用逗號隔開 mc.setRecipientAddresses("xx@qq.com,xxx@163.com"); //設置抄送人地址,多個地址可用逗號隔開 mc.setCopyToAddresses("xxxx@qq.com"); //設置郵件內容 mc.setContent("郵件發送成功啦!"); //設置附件地址,多個附件地址用逗號隔開 String[] s = {"C:/測試附件1.txt","C:/測試附件2.pdf"}; mc.setAttachmentPaths(s);
//郵件信息配置完畢,調用MailUtil發送郵件。
mu.sendMail(mc); } catch (Exception e) { e.printStackTrace(); } } }
運行以上代碼,郵件即可成功發送。
提示:本文展示演示代碼,若需要實際測試,代碼中的“賬號”和“密碼”需更換為自己所使用的郵箱。
代碼GIT CLONE地址:https://github.com/ooo8866923/MailSend.git
以上僅為郵件發送功能的簡單實現,若需進階拓展,或了解底層,需要更進一步查閱相關書籍和網站。
本人能力有限,若文章存在紕漏,或對該文章有任何疑問,批評,建議,衷心渴望您的指教。
本文結束,感謝瀏覽。