利用Java實現(xiàn)電子郵件的批量發(fā)送
JAVA MAIL是利用現(xiàn)有的郵件賬戶發(fā)送郵件的工具,比如說,我在網(wǎng)易注冊一個郵箱賬戶,通過JAVA Mail的操控,我可以不親自登錄網(wǎng)易郵箱,讓程序自動的使用網(wǎng)易郵箱發(fā)送郵件。這一機制被廣泛的用在注冊激活和垃圾郵件的發(fā)送等方面。進行下載,并將mail.jar添加到classpath即可。如果你使用的是JAVA EE SDK,則可以在C:glassfishv3glassfishmodulesmail.jar找到所需的jar包,同樣需要添加的classpath。
JAVA郵件發(fā)送的大致過程是這樣的的:
1、構(gòu)建一個繼承自javax.mail.Authenticator的具體類,并重寫里面的getPasswordAuthentication()方法。此類是用作登錄校驗的,以確保你對該郵箱有發(fā)送郵件的權(quán)利。
2、構(gòu)建一個properties文件,該文件中存放SMTP服務(wù)器地址等參數(shù)。
3、通過構(gòu)建的properties文件和javax.mail.Authenticator具體類來創(chuàng)建一個javax.mail.Session。Session的創(chuàng)建,就相當(dāng)于登錄郵箱一樣。剩下的自然就是新建郵件。
4、構(gòu)建郵件內(nèi)容,一般是javax.mail.internet.MimeMessage對象,并指定發(fā)送人,收信人,主題,內(nèi)容等等。
5、使用javax.mail.Transport工具類發(fā)送郵件。
下面是我封裝的代碼,注釋也比較詳細(xì)。呼呼~~
1、首先是繼承自javax.mail.Authenticator的一個具體類。getPasswordAuthentication()方法也就是構(gòu)建一個PasswordAuthentication對象并返回,有點費解JAVA Mail這樣的設(shè)計意圖,可能是javax.mail.Authenticator為我們提供了附加的保證安全的驗證措施吧。
- package com.mzule.simplemail;
- 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、郵件發(fā)送類,剩下的步驟都是在這個類實現(xiàn)的。代碼中的SimpleMail是封裝了郵件主題和內(nèi)容的一個POJO。覺得在一個方法參數(shù)中既包含主題又包含內(nèi)容,不太合適,故重載了此方法。還有就是因為大多數(shù)郵箱的SMTP服務(wù)器地址都是可以通過郵箱地址算出來,簡單起見,提供了一個不需要SMTP服務(wù)器地址的構(gòu)造器。
- package com.mzule.simplemail;
- import java.util.List;
- import java.util.Properties;
- 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;
- /**
- * 簡單郵件發(fā)送器,可單發(fā),群發(fā)。
- *
- * @author MZULE
- *
- */
- 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ù)郵箱都管用
- final String smtpHostName = "smtp." + username.split("@")[1];
- init(username, password, smtpHostName);
- }
- /**
- * 初始化
- *
- * @param username
- * 發(fā)送郵件的用戶名(地址)
- * @param password
- * 密碼
- * @param smtpHostName
- * SMTP主機地址
- */
- private void init(String username, String password, String smtpHostName) {
- // 初始化props
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.host", smtpHostName);
- // 驗證
- authenticator = new MailAuthenticator(username, password);
- // 創(chuàng)建session
- session = Session.getInstance(props, authenticator);
- }
- /**
- * 發(fā)送郵件
- *
- * @param recipient
- * 收件人郵箱地址
- * @param subject
- * 郵件主題
- * @param content
- * 郵件內(nèi)容
- * @throws AddressException
- * @throws MessagingException
- */
- public void send(String recipient, 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è)置收件人
- 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
- */
- public void send(String recipient, SimpleMail mail)
- throws AddressException, MessagingException {
- 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());
- }
- }
3、調(diào)用上面的郵箱發(fā)送器,可以構(gòu)建一個工廠類,工廠類可以封裝創(chuàng)建的過程,所以通過讀配置文件獲取郵箱用戶名,密碼都會變得十分方便。下面的代碼是我在寫觀察者模式的時候?qū)懙模皇呛唵窝菔玖斯S類。
- package com.mzule.dp.observer.factory;
- import com.mzule.dp.observer.constant.MailSenderType;
- import com.mzule.simplemail.SimpleMailSender;
- /**
- * 發(fā)件箱工廠
- *
- * @author MZULE
- *
- */
- public class MailSenderFactory {
- /**
- * 服務(wù)郵箱
- */
- private static SimpleMailSender serviceSms = null;
- /**
- * 獲取郵箱
- *
- * @param type 郵箱類型
- * @return 符合類型的郵箱
- */
- public static SimpleMailSender getSender(MailSenderType type) {
- if (type == MailSenderType.SERVICE) {
- if (serviceSms == null) {
- serviceSms = new SimpleMailSender("invisible@126.com",
- "hidden");
- }
- return serviceSms;
- }
- return null;
- }
- }
4、發(fā)送郵件,還是觀察者模式DEMO里面的代碼,呼呼。
- package com.mzule.dp.observer.observer;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Observable;
- import java.util.Observer;
- import javax.mail.MessagingException;
- import javax.mail.internet.AddressException;
- import com.mzule.dp.observer.constant.MailSenderType;
- import com.mzule.dp.observer.factory.MailSenderFactory;
- import com.mzule.dp.observer.po.Product;
- import com.mzule.simplemail.SimpleMailSender;
- public class ProductPriceObserver implements Observer {
- @Override
- public void update(Observable obj, Object arg) {
- Product product = null;
- if (obj instanceof Product) {
- product = (Product) obj;
- }
- if (arg instanceof Float) {
- Float price = (Float) arg;
- Float decrease = product.getPrice() - price;
- if (decrease >0) {
- // 發(fā)送郵件
- SimpleMailSender sms = MailSenderFactory
- .getSender(MailSenderType.SERVICE);
- List<String> recipients = new ArrayList<String>();
- recipients.add("invisible@qq.com");
- recipients.add("invisible@gmail.com");
- try {
- for (String recipient : recipients) {
- sms.send(recipient, "價格變動", "您關(guān)注的物品"
- + product.getName() + "降價了,由"
- + product.getPrice() + "元降到" + price + "元,降幅達"
- + decrease + "元人民幣。趕快購物吧。");
- }
- } catch (AddressException e) {
- e.printStackTrace();
- } catch (MessagingException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
5、剩下的就是去查看郵件是否發(fā)送成功了。呼呼~~
原文鏈接:http://www.cnblogs.com/codeplus/archive/2011/10/30/2229391.html
【編輯推薦】