在android開發中如何使用JavaMail程式

來源:互聯網
上載者:User

標籤:sha   cat   步驟   建立檔案夾   port   extend   length   身分識別驗證   i+1   

 javaMail,是提供給開發人員處理電子郵件相關的編程介面。它是Sun發布的用來處理email的API。它可以方便地執行一些常用的郵件傳輸。我們可以基於JavaMail開發出類似於Microsoft outlook的應用程式。JavaMail是可選包,因此如果需要使用的話你需要首先從java官網上下載。

  本文主要介紹JavaMail,javamail發送郵件確實是一個比較麻煩的問題不用第三方郵件程式。為了以後使用方便,自己寫了段代碼

      Javamail-Android配置步驟:

  下載Android版本JavaMail包,additional.jar、mail.jar和activation.jar,JavaMail-Android

  在項目與src同一目錄層級下,建立檔案夾lib,將下載的3個jar包放入該檔案夾

  右鍵->Properties->Java Build Path->Libraries,選擇Add External JARs,找到項目下lib目錄的3個jar包

  My Code有三個類:

  第一個類:MailSenderInfo.java

package com.util.mail;/** * 發送郵件需要使用的基本資料 */import java.util.Properties; public class MailSenderInfo {     // 發送郵件的伺服器的IP和連接埠     private String mailServerHost;     private String mailServerPort = "25";     // 郵件寄件者的地址     private String fromAddress;     // 郵件接收者的地址     private String toAddress;     // 登陸郵件發送伺服器的使用者名稱和密碼     private String userName;     private String password;     // 是否需要身分識別驗證     private boolean validate = false;     // 郵件主題     private String subject;     // 郵件的常值內容     private String content;     // 郵件附件的檔案名稱     private String[] attachFileNames;       /**       * 獲得郵件會話屬性       */    public Properties getProperties(){       Properties p = new Properties();       p.put("mail.smtp.host", this.mailServerHost);       p.put("mail.smtp.port", this.mailServerPort);       p.put("mail.smtp.auth", validate ? "true" : "false");       return p;     }     public String getMailServerHost() {       return mailServerHost;     }     public void setMailServerHost(String mailServerHost) {       this.mailServerHost = mailServerHost;     }    public String getMailServerPort() {       return mailServerPort;     }    public void setMailServerPort(String mailServerPort) {       this.mailServerPort = mailServerPort;     }    public boolean isValidate() {       return validate;     }    public void setValidate(boolean validate) {       this.validate = validate;     }    public String[] getAttachFileNames() {       return attachFileNames;     }    public void setAttachFileNames(String[] fileNames) {       this.attachFileNames = fileNames;     }    public String getFromAddress() {       return fromAddress;     }     public void setFromAddress(String fromAddress) {       this.fromAddress = fromAddress;     }    public String getPassword() {       return password;     }    public void setPassword(String password) {       this.password = password;     }    public String getToAddress() {       return toAddress;     }     public void setToAddress(String toAddress) {       this.toAddress = toAddress;     }     public String getUserName() {       return userName;     }    public void setUserName(String userName) {       this.userName = userName;     }    public String getSubject() {       return subject;     }    public void setSubject(String subject) {       this.subject = subject;     }    public String getContent() {       return content;     }    public void setContent(String textContent) {       this.content = textContent;     } }

  第二個類:MultiMailsender.java

package com.util.mail; import java.util.Date;import java.util.Properties; import javax.mail.Address;import javax.mail.BodyPart;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Multipart;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart; /** * 發送郵件給多個接收者、抄送郵件 */public class MultiMailsender {          /**       * 以文字格式設定發送郵件       * @param mailInfo 待發送的郵件的資訊       */        public boolean sendTextMail(MultiMailSenderInfo mailInfo) {           // 判斷是否需要身份認證           MyAuthenticator authenticator = null;           Properties pro = mailInfo.getProperties();          if (mailInfo.isValidate()) {           // 如果需要身份認證,則建立一個密碼驗證器             authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());           }          // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session           Session sendMailSession = Session.getDefaultInstance(pro,authenticator);           try {           // 根據session建立一個郵件訊息           Message mailMessage = new MimeMessage(sendMailSession);           // 建立郵件寄件者地址           Address from = new InternetAddress(mailInfo.getFromAddress());           // 設定郵件訊息的寄件者           mailMessage.setFrom(from);           // 建立郵件的接收者地址,並設定到郵件訊息中           Address[] tos = null;           String[] receivers = mailInfo.getReceivers();          if (receivers != null){              // 為每個郵件接收者建立一個地址              tos = new InternetAddress[receivers.length + 1];              tos[0] = new InternetAddress(mailInfo.getToAddress());              for (int i=0; i<receivers.length; i++){                  tos[i+1] = new InternetAddress(receivers[i]);              }          } else {              tos = new InternetAddress[1];              tos[0] = new InternetAddress(mailInfo.getToAddress());          }           // Message.RecipientType.TO屬性工作表示接收者的類型為TO           mailMessage.setRecipients(Message.RecipientType.TO,tos);           // 設定郵件訊息的主題           mailMessage.setSubject(mailInfo.getSubject());           // 設定郵件訊息發送的時間           mailMessage.setSentDate(new Date());           // 設定郵件訊息的主要內容           String mailContent = mailInfo.getContent();           mailMessage.setText(mailContent);           // 發送郵件           Transport.send(mailMessage);          return true;           } catch (MessagingException ex) {               ex.printStackTrace();           }           return false;         }     /**     * 發送郵件給多個接收者,以Html內容     * @param mailInfo    帶發送郵件的資訊     * @return     */    public static boolean sendMailtoMultiReceiver(MultiMailSenderInfo mailInfo){        MyAuthenticator authenticator = null;        if (mailInfo.isValidate()) {            authenticator = new MyAuthenticator(mailInfo.getUserName(),                    mailInfo.getPassword());        }        Session sendMailSession = Session.getInstance(mailInfo                .getProperties(), authenticator);        try {            Message mailMessage = new MimeMessage(sendMailSession);            // 建立郵件寄件者地址            Address from = new InternetAddress(mailInfo.getFromAddress());            mailMessage.setFrom(from);            // 建立郵件的接收者地址,並設定到郵件訊息中            Address[] tos = null;            String[] receivers = mailInfo.getReceivers();            if (receivers != null){                // 為每個郵件接收者建立一個地址                tos = new InternetAddress[receivers.length + 1];                tos[0] = new InternetAddress(mailInfo.getToAddress());                for (int i=0; i<receivers.length; i++){                    tos[i+1] = new InternetAddress(receivers[i]);                }            } else {                tos = new InternetAddress[1];                tos[0] = new InternetAddress(mailInfo.getToAddress());            }            // 將所有接收者地址都添加到郵件接收者屬性中            mailMessage.setRecipients(Message.RecipientType.TO, tos);                         mailMessage.setSubject(mailInfo.getSubject());            mailMessage.setSentDate(new Date());            // 設定郵件內容            Multipart mainPart = new MimeMultipart();            BodyPart html = new MimeBodyPart();            html.setContent(mailInfo.getContent(), "text/html; charset=GBK");            mainPart.addBodyPart(html);            mailMessage.setContent(mainPart);            // 發送郵件            Transport.send(mailMessage);            return true;        } catch (MessagingException ex) {            ex.printStackTrace();        }        return false;    }         /**     * 發送帶抄送的郵件     * @param mailInfo    待發送郵件的訊息     * @return     */    public static boolean sendMailtoMultiCC(MultiMailSenderInfo mailInfo){        MyAuthenticator authenticator = null;        if (mailInfo.isValidate()) {            authenticator = new MyAuthenticator(mailInfo.getUserName(),                    mailInfo.getPassword());        }        Session sendMailSession = Session.getInstance(mailInfo                .getProperties(), authenticator);        try {            Message mailMessage = new MimeMessage(sendMailSession);            // 建立郵件寄件者地址            Address from = new InternetAddress(mailInfo.getFromAddress());            mailMessage.setFrom(from);            // 建立郵件的接收者地址,並設定到郵件訊息中            Address to = new InternetAddress(mailInfo.getToAddress());            mailMessage.setRecipient(Message.RecipientType.TO, to);                         // 擷取抄送者資訊            String[] ccs = mailInfo.getCcs();            if (ccs != null){                // 為每個郵件接收者建立一個地址                Address[] ccAdresses = new InternetAddress[ccs.length];                for (int i=0; i<ccs.length; i++){                    ccAdresses[i] = new InternetAddress(ccs[i]);                }                // 將抄送者資訊設定到郵件資訊中,注意類型為Message.RecipientType.CC                mailMessage.setRecipients(Message.RecipientType.CC, ccAdresses);            }                          mailMessage.setSubject(mailInfo.getSubject());            mailMessage.setSentDate(new Date());            // 設定郵件內容            Multipart mainPart = new MimeMultipart();            BodyPart html = new MimeBodyPart();            html.setContent(mailInfo.getContent(), "text/html; charset=GBK");            mainPart.addBodyPart(html);            mailMessage.setContent(mainPart);            // 發送郵件            Transport.send(mailMessage);            return true;        } catch (MessagingException ex) {            ex.printStackTrace();        }        return false;    }         /**     * 發送多接收者類型郵件的基本資料     */    public static class MultiMailSenderInfo extends MailSenderInfo{        // 郵件的接收者,可以有多個        private String[] receivers;        // 郵件的抄送者,可以有多個        private String[] ccs;                 public String[] getCcs() {            return ccs;        }        public void setCcs(String[] ccs) {            this.ccs = ccs;        }        public String[] getReceivers() {            return receivers;        }        public void setReceivers(String[] receivers) {            this.receivers = receivers;        }    }}

  第三個類:MyAuthenticator.java

package com.util.mail;  import javax.mail.*;    public class MyAuthenticator extends Authenticator{    String userName=null;    String password=null;           public MyAuthenticator(){    }    public MyAuthenticator(String username, String password) {         this.userName = username;         this.password = password;     }     protected PasswordAuthentication getPasswordAuthentication(){        return new PasswordAuthentication(userName, password);    }}

  下面給出使用上面三個類的代碼:

public static void main(String[] args){         //這個類主要是設定郵件      MultiMailSenderInfo mailInfo = new MultiMailSenderInfo();       mailInfo.setMailServerHost("smtp.163.com");       mailInfo.setMailServerPort("25");       mailInfo.setValidate(true);       mailInfo.setUserName("[email protected]");       mailInfo.setPassword("**********");//您的郵箱密碼       mailInfo.setFromAddress("[email protected]");       mailInfo.setToAddress("[email protected]");       mailInfo.setSubject("設定郵箱標題");       mailInfo.setContent("設定郵箱內容");      String[] receivers = new String[]{"***@163.com", "***@tom.com"};       String[] ccs = receivers; mailInfo.setReceivers(receivers);       mailInfo.setCcs(ccs);       //這個類主要來發送郵件       MultiMailsender sms = new MultiMailsender();       sms.sendTextMail(mailInfo);//發送文體格式       MultiMailsender.sendHtmlMail(mailInfo);//發送html格式       MultiMailsender.sendMailtoMultiCC(mailInfo);//發送抄送

  最後,給出朋友們幾個注意的地方:

  1、使用此代碼你可以完成你的javamail的郵件發送功能、發多個郵箱。三個類缺一不可。

  2、這三個類我打包是用的com.util.mail包,如果不喜歡,你可以自己改,但三個類檔案必須在同一個包中

  3、不要使用你剛剛註冊過的郵箱在程式中發郵件,如果你的163郵箱是剛註冊不久,那你就不要使用“smtp.163.com”。因為你發不出去。剛註冊的郵箱是不會給你這種許可權的,也就是你不能通過驗證。要使用你經常用的郵箱,而且時間比較長的。

  4、另一個問題就是mailInfo.setMailServerHost("smtp.163.com");與mailInfo.setFromAddress("[email protected]");這兩句話。即如果你使用163smtp伺服器,那麼發送郵件地址就必須用163的郵箱,如果不的話,是不會發送成功的。

  5、關於javamail驗證錯誤的問題,網上的解釋有很多,但我看見的只有一個。就是我的第三個類。你只要複製全了代碼,我想是不會有問題的。

  6、 然後在Android項目中添加網路存取權限

  本文主要介紹了Javamail-Android配置步驟和三個類的代碼,最後給出了六點建議,希望我們在android開發中使用JavaMail程式需要注意的一些問題。

 

在android開發中如何使用JavaMail程式

聯繫我們

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