Java Mail郵件發(fā)送如何實現(xiàn)簡單封裝
首先每次發(fā)送需要配置的東西很多,包括發(fā)件人的郵箱和密碼、smtp服務(wù)器和SMTP端口號等信息。其次,沒有將發(fā)送和郵件內(nèi)容相分離。按照單一職責(zé)原則,應(yīng)該有且僅有一個原因引起類的變更[1]。最后一個問題是,我們的代碼不僅自己用,也很可能讓別人調(diào)用。別人調(diào)用的時候不想去了解郵件發(fā)送的細節(jié),調(diào)用的人只想傳盡量少的參數(shù)獲得預(yù)期的效果。因此讓Demo變成可以使用的代碼需要我們重新設(shè)計代碼的結(jié)構(gòu)。
從Demo中我們可以抽象出兩種類型的POJO,也就是發(fā)件人和郵件。你可能會問收件人怎么辦?收件人可以跟郵件POJO放在一起嗎?
仔細思考下我們就知道,郵件和收件人應(yīng)該是分開的。因為如果郵件和收件人放在一起,那么就意味著我的一封郵件只能發(fā)送給特定的人了,而實際上我們會把相同的郵件發(fā)送給不同的收件人。因此收件人只要作為發(fā)送時的參數(shù)就可以了。
1.發(fā)件人POJO
/** * @Title: MailAuthenticator * @author: ykgao * @description: * @date: 2017-10-11 下午04:55:37 */import javax.mail.Authenticator;import javax.mail.PasswordAuthentication; /** * 服務(wù)器郵箱登錄驗證 * * @author MZULE * */public class MailAuthenticator extends Authenticator { /** * 用戶名(登錄郵箱) */ private String username; /** * 密碼 */ private String password; /** * 初始化郵箱和密碼 * * @param username 郵箱 * @param password 密碼 */ public MailAuthenticator(String username, String password) { this.username = username; this.password = password; } String getPassword() { return password; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public void setUsername(String username) { this.username = username; } }
2.郵件POJO
用于存儲郵件主題和內(nèi)容。
/** * @Title: SimpleMail * @author: ykgao * @description: * @date: 2017-10-11 下午04:56:27 */public class SimpleMail {/** 郵件主題 */public String Subject;/** 郵件內(nèi)容 */public String Content;/** * @return the subject */public String getSubject() {return Subject;}/** * @param subject * the subject to set */public void setSubject(String subject) {Subject = subject;}/** * @return the content */public String getContent() {return Content;}/** * @param content * the content to set */public void setContent(String content) {Content = content;}}
3.郵件發(fā)送
設(shè)計好了POJO,我們現(xiàn)在需要當(dāng)然是發(fā)送郵件了。在Demo中我們需要配置SMTP服務(wù)器,但是我們使用郵箱發(fā)送郵件的時候并不需要填寫SMTP服務(wù)器。其實SMTP服務(wù)器大多數(shù)的格式是:smtp.emailType.com。此處emailType 就是你的郵箱類型也就是@后面跟的名稱。比如163郵箱就是163。不過這個方法也不是萬能的,因為outlook郵箱的smtp服務(wù)器就不是這個格式,而是smtp-mail.outlook.com ,所以我單獨為outlook郵箱寫了個例外。
我們還需要群分郵件的功能。這個設(shè)計起來很容易,只需要一個單人發(fā)送的重載方法,其收件人的參數(shù)可以是一個List。為了減少接口的參數(shù)個數(shù),我們把SMTP端口默認為587。
import java.io.UnsupportedEncodingException;import java.security.GeneralSecurityException;import java.util.List;import java.util.Properties;import javaMailDevelopment.SimpleMail;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMessage.RecipientType;import com.sun.mail.util.MailSSLSocketFactory;/** * @Title: SimpleMailSender * @author: ykgao * @description: 郵件發(fā)送器 * @date: 2017-10-11 下午04:54:50 */public class SimpleMailSender {/** * 發(fā)送郵件的props文件 */private final transient Properties props = System.getProperties();/** * 郵件服務(wù)器登錄驗證 */private transient MailAuthenticator authenticator;/** * 郵箱session */private transient Session session;/** * 初始化郵件發(fā)送器 * * @param smtpHostName * SMTP郵件服務(wù)器地址 * @param username * 發(fā)送郵件的用戶名(地址) * @param password * 發(fā)送郵件的密碼 */public SimpleMailSender(final String smtpHostName, final String username, final String password) {init(username, password, smtpHostName);}/** * 初始化郵件發(fā)送器 * * @param username * 發(fā)送郵件的用戶名(地址),并以此解析SMTP服務(wù)器地址 * @param password * 發(fā)送郵件的密碼 */public SimpleMailSender(final String username, final String password) {// 通過郵箱地址解析出smtp服務(wù)器,對大多數(shù)郵箱都管用String smtpHostName = 'smtp.' + username.split('@')[1];if (username.split('@')[1].equals('outlook.com')) {smtpHostName = 'smtp-mail.outlook.com';}init(username, password, smtpHostName);}/** * 初始化 * * @param username * 發(fā)送郵件的用戶名(地址) * @param password * 密碼 * @param smtpHostName * SMTP主機地址 */private void init(String username, String password, String smtpHostName) {// 初始化propsprops.setProperty('mail.transport.protocol', 'smtp'); // 使用的協(xié)議(JavaMail規(guī)范要求)props.setProperty('mail.smtp.host', smtpHostName); // 發(fā)件人的郵箱的 SMTP 服務(wù)器地址props.setProperty('mail.smtp.auth', 'true'); // 需要請求認證final String smtpPort = '587';props.setProperty('mail.smtp.port', smtpPort);// props.setProperty('mail.smtp.socketFactory.class',// 'javax.net.ssl.SSLSocketFactory');props.setProperty('mail.smtp.socketFactory.fallback', 'false');props.setProperty('mail.smtp.starttls.enable', 'true');props.setProperty('mail.smtp.socketFactory.port', smtpPort);// 驗證authenticator = new MailAuthenticator(username, password);// 創(chuàng)建sessionsession = Session.getInstance(props, authenticator);session.setDebug(true);}/** * 發(fā)送郵件 * * @param recipient * 收件人郵箱地址 * @param subject * 郵件主題 * @param content * 郵件內(nèi)容 * @throws AddressException * @throws MessagingException * @throws UnsupportedEncodingException */public void send(String recipient, String subject, Object content) throws Exception {// 創(chuàng)建mime類型郵件final MimeMessage message = new MimeMessage(session);// 設(shè)置發(fā)信人message.setFrom(new InternetAddress(authenticator.getUsername()));// 設(shè)置收件人message.setRecipient(RecipientType.TO, new InternetAddress(recipient));// 設(shè)置主題message.setSubject(subject);// 設(shè)置郵件內(nèi)容message.setContent(content.toString(), 'text/html;charset=utf-8');// 發(fā)送Transport.send(message);}/** * 群發(fā)郵件 * * @param recipients * 收件人們 * @param subject * 主題 * @param content * 內(nèi)容 * @throws AddressException * @throws MessagingException */public void send(List<String> recipients, String subject, Object content)throws AddressException, MessagingException {// 創(chuàng)建mime類型郵件final MimeMessage message = new MimeMessage(session);// 設(shè)置發(fā)信人message.setFrom(new InternetAddress(authenticator.getUsername()));// 設(shè)置收件人們final int num = recipients.size();InternetAddress[] addresses = new InternetAddress[num];for (int i = 0; i < num; i++) {addresses[i] = new InternetAddress(recipients.get(i));}message.setRecipients(RecipientType.TO, addresses);// 設(shè)置主題message.setSubject(subject);// 設(shè)置郵件內(nèi)容message.setContent(content.toString(), 'text/html;charset=utf-8');// 發(fā)送Transport.send(message);}/** * 發(fā)送郵件 * * @param recipient * 收件人郵箱地址 @param mail 郵件對象 @throws AddressException @throws * MessagingException @throws */public void send(String recipient, SimpleMail mail) throws Exception {send(recipient, mail.getSubject(), mail.getContent());}/** * 群發(fā)郵件 * * @param recipients * 收件人們 * @param mail * 郵件對象 * @throws AddressException * @throws MessagingException */public void send(List<String> recipients, SimpleMail mail) throws AddressException, MessagingException {send(recipients, mail.getSubject(), mail.getContent());}}
4.測試代碼
代碼寫完了,現(xiàn)在需要測試下代碼是否可行。
import java.util.ArrayList;import java.util.List;/** * @Title: testMail * @author: ykgao * @description: * @date: 2017-10-11 下午02:13:02 * */public class testMail {public static void main(String[] args) throws Exception { /** 創(chuàng)建一個郵件發(fā)送者*/SimpleMailSender simpleMailSeJava Mail 郵件發(fā)送簡單封裝
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 使用.net core 自帶DI框架實現(xiàn)延遲加載功能2. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究3. Angular獲取ngIf渲染的Dom元素示例4. php面向?qū)ο蟪绦蛟O(shè)計介紹5. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp6. 無線標記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁7. 三個不常見的 HTML5 實用新特性簡介8. php測試程序運行速度和頁面執(zhí)行速度的代碼9. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析10. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析
