Java郵件開發—–JavaMail(二)

來源:互聯網
上載者:User

          這篇部落客要是介紹如何?將郵件發送給多個收件者和如何利用Authenticators對象實現使用者驗證。   

         在指定收件者的時候,我們可以有兩種方法來指定。上篇部落格是在發送郵件的時候臨時指定收件者,其實還可以在Message對象中指定。

 

1 message.addRecipient(Message.RecipientType.TO,new InternetAddress(” 995812509@99.com ”));

 

 

         這個只是發送給一個收件者而言,但是有多個收件者如何處理?同樣有兩種方法來處理。

          1、在發送郵件時Transport的sendMessage()方法指定收件者時是使用數組來指定收件者的,這個時候我們只需要多添加收件者地址即可完成。

          2、在使用Message對象來添加收件者我們可以使用InternetAddress對象的parse(String string)方法,該方法返回的是InternetAddress數組,這樣同樣可以實現發送給多個收件者。

 

         我們知道在進行JavaMail開發時我們必須要進行授權校正,授權校正目的是阻止他人任意亂髮郵件,減少垃圾郵件的產生。前篇部落格中我是是用的Transport的connect(host,port,username,password)方法來進行校正的,其實我們還可以在擷取Session對象的時候進行校正。在Session對象中有這兩個方法:getDefaultInstance(prop,authenticator),getInstance(prop,authenticator),這兩個方法都有一個共同的參數authenticator,該參數是一個Authenticator對象。Authenticator對象就是協助使用者進行資訊驗證的,完成授權校正。Authenticator對象中有getPasswordAuthentication()方法,該方法返回返回一個PasswordAuthentication對象,PasswordAuthentication對象中有兩個方法:getPassword()、getUserName()也就說我們將password、userName封裝在PasswordAuthentication對象,通過這兩個方法就可以擷取使用者名稱和密碼了。即可完成使用者資訊驗證。

          執行個體如下:

 1 public class JavaMail_02 { 2     public static void main(String[] args) throws Exception { 3         Properties  props = new Properties(); 4         props.setProperty("mail.smtp.auth", "true"); 5         props.setProperty("mail.transport.protocol", "smtp"); 6         props.setProperty("mail.host", "smtp.163.com"); 7          8         Session session = Session.getInstance(props, 9                 new Authenticator(){10                     protected PasswordAuthentication getPasswordAuthentication(){11                         return new PasswordAuthentication("********","*********");12                     }13         });14         session.setDebug(true);15         16         Message msg = new MimeMessage(session);17         msg.setFrom(new InternetAddress("chenssy995812509@163.com"));18         19         msg.setSubject("JavaMail測試程式...");20         msg.setContent("<span style='color:red'>這是我的第二個javaMail測試程式....</span>", "text/html;charset=gbk");21         //msg.setRecipients(RecipientType.TO, new Address[]{new InternetAddress("1111@@qq.com"),new InternetAddress("2222@qq.cpm")});22         msg.setRecipients(RecipientType.TO, InternetAddress.parse("995812509@qq.com,1247723213@qq.com"));23         24         Transport.send(msg);25     }26 27 }

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.