qileilove

          blog已經(jīng)轉移至github,大家請訪問 http://qaseven.github.io/

          利用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、構建一個繼承自javax.mail.Authenticator的具體類,并重寫里面的getPasswordAuthentication()方法。此類是用作登錄校驗的,以確保你對該郵箱有發(fā)送郵件的權利。

            2、構建一個properties文件,該文件中存放SMTP服務器地址等參數(shù)。

            3、通過構建的properties文件和javax.mail.Authenticator具體類來創(chuàng)建一個javax.mail.Session。Session的創(chuàng)建,就相當于登錄郵箱一樣。剩下的自然就是新建郵件。

            4、構建郵件內(nèi)容,一般是javax.mail.internet.MimeMessage對象,并指定發(fā)送人,收信人,主題,內(nèi)容等等。

            5、使用javax.mail.Transport工具類發(fā)送郵件。

            下面是我封裝的代碼,注釋也比較詳細。呼呼~~

            1、首先是繼承自javax.mail.Authenticator的一個具體類。getPasswordAuthentication()方法也就是構建一個PasswordAuthentication對象并返回,有點費解JAVA Mail這樣的設計意圖,可能是javax.mail.Authenticator為我們提供了附加的保證安全的驗證措施吧。

          1. package com.mzule.simplemail;  
          2. import javax.mail.Authenticator;  
          3. import javax.mail.PasswordAuthentication;  
          4. /** 
          5. * 服務器郵箱登錄驗證 
          6. * 
          7. * @author MZULE 
          8. * 
          9. */ 
          10. public class MailAuthenticator extends Authenticator {  
          11. /** 
          12. * 用戶名(登錄郵箱) 
          13. */ 
          14. private String username;  
          15. /** 
          16. * 密碼 
          17. */ 
          18. private String password;  
          19. /** 
          20. * 初始化郵箱和密碼 
          21. * 
          22. * @param username 郵箱 
          23. * @param password 密碼 
          24. */ 
          25. public MailAuthenticator(String username, String password) {  
          26. this.username = username;  
          27. this.password = password;  
          28. }  
          29. String getPassword() {  
          30. return password;  
          31. }  
          32. @Override 
          33. protected PasswordAuthentication getPasswordAuthentication() {  
          34. return new PasswordAuthentication(username, password);  
          35. }  
          36. String getUsername() {  
          37. return username;  
          38. }  
          39. public void setPassword(String password) {  
          40. this.password = password;  
          41. }  
          42. public void setUsername(String username) {  
          43. this.username = username;  
          44. }  
          45. }

           2、郵件發(fā)送類,剩下的步驟都是在這個類實現(xiàn)的。代碼中的SimpleMail是封裝了郵件主題和內(nèi)容的一個POJO。覺得在一個方法參數(shù)中既包含主題又包含內(nèi)容,不太合適,故重載了此方法。還有就是因為大多數(shù)郵箱的SMTP服務器地址都是可以通過郵箱地址算出來,簡單起見,提供了一個不需要SMTP服務器地址的構造器。

          1. package com.mzule.simplemail;  
          2. import java.util.List;  
          3. import java.util.Properties;  
          4. import javax.mail.MessagingException;  
          5. import javax.mail.Session;  
          6. import javax.mail.Transport;  
          7. import javax.mail.internet.AddressException;  
          8. import javax.mail.internet.InternetAddress;  
          9. import javax.mail.internet.MimeMessage;  
          10. import javax.mail.internet.MimeMessage.RecipientType;  
          11. /**  
          12. * 簡單郵件發(fā)送器,可單發(fā),群發(fā)。  
          13.  
          14. * @author MZULE  
          15.  
          16. */ 
          17. public class SimpleMailSender {  
          18. /**  
          19. * 發(fā)送郵件的props文件  
          20. */ 
          21. private final transient Properties props = System.getProperties();  
          22. /**  
          23. * 郵件服務器登錄驗證  
          24. */ 
          25. private transient MailAuthenticator authenticator;  
          26. /**  
          27. * 郵箱session  
          28. */ 
          29. private transient Session session;  
          30. /**  
          31. * 初始化郵件發(fā)送器  
          32.  
          33. * @param smtpHostName  
          34. * SMTP郵件服務器地址  
          35. * @param username  
          36. * 發(fā)送郵件的用戶名(地址)  
          37. * @param password  
          38. * 發(fā)送郵件的密碼  
          39. */ 
          40. public SimpleMailSender(final String smtpHostName, final String username,  
          41. final String password) {  
          42. init(username, password, smtpHostName);  
          43. }  
          44. /**  
          45. * 初始化郵件發(fā)送器  
          46.  
          47. * @param username  
          48. * 發(fā)送郵件的用戶名(地址),并以此解析SMTP服務器地址  
          49. * @param password  
          50. * 發(fā)送郵件的密碼  
          51. */ 
          52. public SimpleMailSender(final String username, final String password) {  
          53. //通過郵箱地址解析出smtp服務器,對大多數(shù)郵箱都管用  
          54. final String smtpHostName = "smtp." + username.split("@")[1];  
          55. init(username, password, smtpHostName);  
          56. }  
          57. /**  
          58. * 初始化  
          59.  
          60. * @param username  
          61. * 發(fā)送郵件的用戶名(地址)  
          62. * @param password  
          63. * 密碼  
          64. * @param smtpHostName  
          65. * SMTP主機地址  
          66. */ 
          67. private void init(String username, String password, String smtpHostName) {  
          68. // 初始化props  
          69. props.put("mail.smtp.auth""true");  
          70. props.put("mail.smtp.host", smtpHostName);  
          71. // 驗證  
          72. authenticator = new MailAuthenticator(username, password);  
          73. // 創(chuàng)建session  
          74. session = Session.getInstance(props, authenticator);  
          75. }  
          76. /**  
          77. * 發(fā)送郵件  
          78.  
          79. * @param recipient  
          80. * 收件人郵箱地址  
          81. * @param subject  
          82. * 郵件主題  
          83. * @param content  
          84. * 郵件內(nèi)容  
          85. * @throws AddressException  
          86. * @throws MessagingException  
          87. */ 
          88. public void send(String recipient, String subject, Object content)  
          89. throws AddressException, MessagingException {  
          90. // 創(chuàng)建mime類型郵件  
          91. final MimeMessage message = new MimeMessage(session);  
          92. // 設置發(fā)信人  
          93. message.setFrom(new InternetAddress(authenticator.getUsername()));  
          94. // 設置收件人  
          95. message.setRecipient(RecipientType.TO, new InternetAddress(recipient));  
          96. // 設置主題  
          97. message.setSubject(subject);  
          98. // 設置郵件內(nèi)容  
          99. message.setContent(content.toString(), "text/html;charset=utf-8");  
          100. // 發(fā)送  
          101. Transport.send(message);  
          102. }  
          103. /**  
          104. * 群發(fā)郵件  
          105.  
          106. * @param recipients  
          107. * 收件人們  
          108. * @param subject  
          109. * 主題  
          110. * @param content  
          111. * 內(nèi)容  
          112. * @throws AddressException  
          113. * @throws MessagingException  
          114. */ 
          115. public void send(List<String> recipients, String subject, Object content)  
          116. throws AddressException, MessagingException {  
          117. // 創(chuàng)建mime類型郵件  
          118. final MimeMessage message = new MimeMessage(session);  
          119. // 設置發(fā)信人  
          120. message.setFrom(new InternetAddress(authenticator.getUsername()));  
          121. // 設置收件人們  
          122. final int num = recipients.size();  
          123.  InternetAddress[] addresses = new InternetAddress[num];  
          124. for (int i = 0; i <num; i++) {  
          125. addresses[i] = new InternetAddress(recipients.get(i));  
          126. }  
          127. message.setRecipients(RecipientType.TO, addresses);  
          128. // 設置主題  
          129. message.setSubject(subject);  
          130. // 設置郵件內(nèi)容  
          131. message.setContent(content.toString(), "text/html;charset=utf-8");  
          132. // 發(fā)送  
          133. Transport.send(message);  
          134. }  
          135. /**  
          136. * 發(fā)送郵件  
          137.  
          138. * @param recipient  
          139. * 收件人郵箱地址  
          140. * @param mail  
          141. * 郵件對象  
          142. * @throws AddressException  
          143. * @throws MessagingException  
          144.  */ 
          145. public void send(String recipient, SimpleMail mail)  
          146. throws AddressException, MessagingException {  
          147. send(recipient, mail.getSubject(), mail.getContent());  
          148. }  
          149. /**  
          150. * 群發(fā)郵件  
          151.  
          152. * @param recipients  
          153. * 收件人們  
          154. * @param mail  
          155.  * 郵件對  
          156.  * @throws AddressException  
          157. * @throws MessagingException  
          158. */ 
          159. public void send(List<String> recipients, SimpleMail mail)  
          160. throws AddressException, MessagingException {  
          161. send(recipients, mail.getSubject(), mail.getContent());  
          162. }  
          163. }

          3、調(diào)用上面的郵箱發(fā)送器,可以構建一個工廠類,工廠類可以封裝創(chuàng)建的過程,所以通過讀配置文件獲取郵箱用戶名,密碼都會變得十分方便。下面的代碼是我在寫觀察者模式的時候寫的,只是簡單演示了工廠類。

          1.  package com.mzule.dp.observer.factory;  
          2. import com.mzule.dp.observer.constant.MailSenderType;  
          3. import com.mzule.simplemail.SimpleMailSender;  
          4. /**  
          5. * 發(fā)件箱工廠  
          6.  
          7. * @author MZULE  
          8.  
          9. */ 
          10. public class MailSenderFactory {  
          11. /**  
          12. * 服務郵箱  
          13. */ 
          14. private static SimpleMailSender serviceSms = null;  
          15. /**  
          16. * 獲取郵箱  
          17.  
          18. * @param type 郵箱類型  
          19. * @return 符合類型的郵箱  
          20. */ 
          21. public static SimpleMailSender getSender(MailSenderType type) {  
          22. if (type == MailSenderType.SERVICE) {  
          23. if (serviceSms == null) {  
          24. serviceSms = new SimpleMailSender("invisible@126.com",  
          25. "hidden");  
          26. }  
          27. return serviceSms;  
          28. }  
          29. return null;  
          30. }  
          31. }

            4、發(fā)送郵件,還是觀察者模式DEMO里面的代碼,呼呼。

          1. package com.mzule.dp.observer.observer;  
          2. import java.util.ArrayList;  
          3. import java.util.List;  
          4. import java.util.Observable;  
          5. import java.util.Observer;  
          6. import javax.mail.MessagingException;  
          7. import javax.mail.internet.AddressException;  
          8. import com.mzule.dp.observer.constant.MailSenderType;  
          9. import com.mzule.dp.observer.factory.MailSenderFactory;  
          10. import com.mzule.dp.observer.po.Product;  
          11. import com.mzule.simplemail.SimpleMailSender;  
          12. public class ProductPriceObserver implements Observer {  
          13. @Override 
          14. public void update(Observable obj, Object arg) {  
          15. Product product = null;  
          16. if (obj instanceof Product) {  
          17. product = (Product) obj;  
          18. }  
          19. if (arg instanceof Float) {  
          20. Float price = (Float) arg;  
          21.  Float decrease = product.getPrice() - price;  
          22. if (decrease >0) {  
          23. // 發(fā)送郵件  
          24. SimpleMailSender sms = MailSenderFactory  
          25. .getSender(MailSenderType.SERVICE);  
          26. List<String> recipients = new ArrayList<String>();  
          27. recipients.add("invisible@qq.com");  
          28. recipients.add("invisible@gmail.com");  
          29. try {  
          30. for (String recipient : recipients) {  
          31. sms.send(recipient, "價格變動""您關注的物品" 
          32. + product.getName() + "降價了,由" 
          33. + product.getPrice() + "元降到" + price + "元,降幅達" 
          34. + decrease + "元人民幣。趕快購物吧。");  
          35. }  
          36. catch (AddressException e) {  
          37. e.printStackTrace();  
          38. catch (MessagingException e) {  
          39. e.printStackTrace();  
          40. }  
          41. }  
          42. }  
          43. }  
          44. }

          posted on 2011-11-03 09:23 順其自然EVO 閱讀(2810) 評論(2)  編輯  收藏

          評論

          # re: 利用Java實現(xiàn)電子郵件的批量發(fā)送 2013-08-04 11:43 罵咯

          我看看 試試 不知道 怎么呀 來啊
          www.minglu5.com名錄屋
          bbs.ibbcp.com影視劇發(fā)行  回復  更多評論   

          # re: 利用Java實現(xiàn)電子郵件的批量發(fā)送 2014-01-06 21:27 miciing

          不錯!  回復  更多評論   


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           
          <2011年11月>
          303112345
          6789101112
          13141516171819
          20212223242526
          27282930123
          45678910

          導航

          統(tǒng)計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 高清| 潜山县| 舞阳县| 兴文县| 永泰县| 颍上县| 长寿区| 临湘市| 乌兰浩特市| 梅河口市| 新巴尔虎右旗| 临西县| 崇信县| 密云县| 抚远县| 井冈山市| 同仁县| 岐山县| 阳曲县| 沧州市| 滦平县| 敦煌市| 大理市| 潮州市| 仁寿县| 南城县| 来安县| 吐鲁番市| 阿合奇县| 乃东县| 卢氏县| 金秀| 黄陵县| 太仓市| 陕西省| 彭泽县| 涿鹿县| 福州市| 潼关县| 太湖县| 揭阳市|