Java中使用JavaMail多發郵件及郵件的驗證和附件實現_java

來源:互聯網
上載者:User

多發和使用者驗證
下面先來介紹如何?將郵件發送給多個收件者和如何利用Authenticators對象實現使用者驗證。  
指定收件者的時候,我們可以有兩種方法來指定。上篇部落格是在發送郵件的時候臨時指定收件者,其實還可以在Message對象中指定。

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

         這個只是發送給一個收件者而言,但是有多個收件者如何處理?同樣有兩種方法來處理。
          1、在發送郵件時Transport的sendMessage()方法指定收件者時是使用數組來指定收件者的,這個時候我們只需要多添加收件者地址即可完成。
          2、在使用Message對象來添加收件者我們可以使用InternetAddress對象的parse(String string)方法,該方法返回的是InternetAddress數組,這樣同樣可以實現發送給多個收件者。
 
         我們知道在進行JavaMail開發時我們必須要進行授權校正,授權校正目的是阻止他人任意亂髮郵件,減少垃圾郵件的產生。
我們可以在擷取Session對象的時候進行校正。在Session對象中有這兩個方法:

  • getDefaultInstance(prop,authenticator),
  • getInstance(prop,authenticator),

這兩個方法都有一個共同的參數authenticator,該參數是一個Authenticator對象。Authenticator對象就是協助使用者進行資訊驗證的,完成授權校正。Authenticator對象中有getPasswordAuthentication()方法,該方法返回返回一個PasswordAuthentication對象,PasswordAuthentication對象中有兩個方法:getPassword()、getUserName()也就說我們將password、userName封裝在PasswordAuthentication對象,通過這兩個方法就可以擷取使用者名稱和密碼了。即可完成使用者資訊驗證。

 執行個體如下:

public class JavaMail_02 {   public static void main(String[] args) throws Exception {     Properties props = new Properties();     props.setProperty("mail.smtp.auth", "true");     props.setProperty("mail.transport.protocol", "smtp");     props.setProperty("mail.host", "smtp.163.com");          Session session = Session.getInstance(props,         new Authenticator(){           protected PasswordAuthentication getPasswordAuthentication(){             return new PasswordAuthentication("********","*********");           }     });     session.setDebug(true);          Message msg = new MimeMessage(session);     msg.setFrom(new InternetAddress("chenssy995812509@163.com"));          msg.setSubject("JavaMail測試程式...");     msg.setContent("<span style='color:red'>這是我的第二個javaMail測試程式....</span>", "text/html;charset=gbk");     //msg.setRecipients(RecipientType.TO, new Address[]{new InternetAddress("1111@@qq.com"),new InternetAddress("2222@qq.cpm")});     msg.setRecipients(RecipientType.TO, InternetAddress.parse("995812509@qq.com,1247723213@qq.com"));          Transport.send(msg);   }  } 

 

帶有圖片和附件的郵件
在實際的電子郵件中我們一般都會涉及到更加複雜電子郵件結構,例如有附件、郵件內文裡麵包含圖片、包含歌曲等等,在這個時候我們就必須要對郵件的結構有著很清晰的認識。在進行複合郵件開發之前需要對複合郵件的結構有一定的瞭解。

       上面這幅圖片展示了一封複合郵件的整體結構,我們可以看出一封複雜的電子郵件由多個部分組成。它有一個頭部和本文,但是本文並不是像以前那麼簡單了,而是由幾個部分組成。頭部需要起到一個指示的作用,它需要說明本文需要使用什麼樣的分隔字元來分開,本文幾個部分之間使用什麼樣的組合關係。對於上面電子郵件它由三個部分組成,每一部分都有自己頭和體,第一部分也由兩個部分組成。
 
         複合郵件的組合關係:
         本文部分之間有多種組合關係。組合關係如下圖:

alternative:選擇關係。上面的純文字和超文本之間就是一種選擇關係。
        related:關聯關係。假如上面的超文本本文是展示一幅圖片,那麼我們在發送郵件的時候必須要將這幅圖片包含到郵件中,也就是所謂的內嵌資源,這個內嵌資源是給超文本用的。所以他們兩者之間是一個關聯關係。
        mixed:混合關係。在純文字、超文本和內嵌資源群組成一個整體和,他們與附件並列著,兩者之間就是一個混合關係了。
 
        複合郵件組織圖的API:

  MimeMessage類表示整封電子郵件。
        MimeBodyPart類表示郵件的一個MiME訊息。
        MimeMultipart類表示一個由多個MIME訊息組合成的組合MIME訊息。
 
        下面一個執行個體:該郵件裡麵包含兩個附件、本文部分包括純文字和超文本,超文本表示展示一張圖片。原始碼如下:

public class JavaMail_03 {    public static void main(String[] args) throws Exception {     Properties props = new Properties();     props.setProperty("mail.smtp.auth", "true");     props.setProperty("mail.transport.protocol", "smtp");     props.setProperty("mail.host", "smtp.163.com");     Session session = Session.getInstance(props,         new Authenticator(){           protected PasswordAuthentication getPasswordAuthentication(){             return new PasswordAuthentication("*****","******");           }     });          Message message = new MimeMessage(session);     message.setSubject("第三個JavaMail測試程式");     message.setFrom(new InternetAddress("\""+MimeUtility.encodeText("陳明")+"\"<chenssy995812509@163.com>"));     message.setRecipients(RecipientType.TO, new Address[]{new InternetAddress("995812509@qq.com")});          //郵件內文     MimeMultipart multipart = new MimeMultipart("mixed");     message.setContent(multipart);     /*      * 建立郵件的內容      * 包括一個郵件內文和兩個附件      */     MimeBodyPart content = new MimeBodyPart();   //郵件內容     MimeBodyPart attch1 = new MimeBodyPart();   //附件1     MimeBodyPart attch2 = new MimeBodyPart();   //附件2     //將郵件內容添加到multipart中     multipart.addBodyPart(content);     multipart.addBodyPart(attch1);     multipart.addBodyPart(attch2);          //設定附件1     DataSource ds1 = new FileDataSource("G:\\電子書\\oracle口令.txt");     DataHandler dh1 = new DataHandler(ds1);     attch1.setDataHandler(dh1);     attch1.setFileName("oracle.txt");     //設定附件2     DataSource ds2 = new FileDataSource("G:\\電子書\\帳號.txt");     DataHandler dh2 = new DataHandler(ds2);     attch2.setDataHandler(dh2);     attch2.setFileName(MimeUtility.encodeText("帳號.txt"));     /*      * 設定內容(本文)---是一個複雜體      * 包括HTML本文和顯示一張圖片      */     MimeMultipart bodyMultipart = new MimeMultipart("related");     content.setContent(bodyMultipart);     //構造本文     MimeBodyPart htmlBody = new MimeBodyPart();     MimeBodyPart gifBody = new MimeBodyPart();     bodyMultipart.addBodyPart(htmlBody);     bodyMultipart.addBodyPart(gifBody);        //設定圖片     DataSource gifds = new FileDataSource("F:\\圖片\\圖片\\4.jpg");     DataHandler gifdh = new DataHandler(gifds);     gifBody.setDataHandler(gifdh);     gifBody.setHeader("Content-ID", "<"+gifds.getName()+">");     //gifBody.setHeader("Content-Location", "http://www.itcast.cn/logo.gif");     //設定HTML本文     htmlBody.setContent("<span style='color:red;font-size:16px'>這是我的第三個JavaMail測試哦!包括了附件和圖片,有點兒複雜...</span><br>" +         "顯示的圖片<img src='cid:4.jpg'/>", "text/html;charset=UTF-8");               message.saveChanges();    //產生郵件     Transport.send(message);   }  } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.