Android 中發送郵件


第一步、導入第三方jar包

Android實現發送郵件,首先需要依賴additional.jar、mail.jar和activation.jar這3個jar包。

Google提供了下載地址:https://code.google.com/archive/p/javamail-android/downloads 。

下載后添加到依賴(這里我就不詳細說明了)。

第二步、創建相關類

1、創建MailInfo類,來代表一個即將被發送的郵件

package com.chuanye.maidian.mail;

import java.util.Properties;

public class MailInfo {
    private String mailServerHost;// 發送郵件的服務器的IP
    private String mailServerPort;// 發送郵件的服務器的端口
    private String fromAddress;// 郵件發送者的地址
    private String toAddress;	// 郵件接收者的地址
    private String userName;// 登陸郵件發送服務器的用戶名
    private String password;// 登陸郵件發送服務器的密碼
    private boolean validate = true;// 是否需要身份驗證
    private String subject;// 郵件主題
    private String content;// 郵件的文本內容
    private String[] attachFileNames;// 郵件附件的文件名

    /**
     * 獲得郵件會話屬性
     */
    public Properties getProperties() {
        Properties p = new Properties();

        //p.put("mail.pop.host", this.mailServerHost);
        p.put("mail.smtp.host", this.mailServerHost);
        p.put("mail.smtp.port", this.mailServerPort);
        //p.put("mail.smtp.auth", validate ? "true" : "false");
        p.put("mail.smtp.auth", "true");//設置為true 才被允許,默認false

        //p.put("mail.smtp.socketFactory.class", SSL_FACTORY); // 使用JSSE的SSL
        /*p.put("mail.smtp.socketFactory.fallback", "false"); // 只處理SSL的連接,對於非SSL的連接不做處理
        p.put("mail.smtp.socketFactory.port", this.mailServerPort);
        p.put("mail.smtp.ssl.enable", true);*/
        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;
    }
}

  2、創建認證類MyAuthenticator

package com.chuanye.maidian.mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

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);
    }
}

  3、創建郵件發送類MailSender

package com.chuanye.maidian.mail;

import android.util.Log;

import java.io.File;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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;
import javax.mail.internet.MimeUtility;

public class MailSender {
    /**
     * 以文本格式發送郵件
     * @param mailInfo 待發送的郵件的信息
     */
    public boolean sendTextMail(final MailInfo 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);

//		Session sendMailSession = Session.getInstance(pro, new Authenticator() {
//			@Override
//			protected PasswordAuthentication getPasswordAuthentication() {
//				return new PasswordAuthentication(mailInfo.getUserName(),mailInfo.getPassword());
//			}
//		});

        try {
            // 根據session創建一個郵件消息
            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);
            // 設置郵件消息的主題
            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 待發送的郵件信息
     */
    public static boolean sendHtmlMail(MailInfo 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 to = new InternetAddress(mailInfo.getToAddress());
            // Message.RecipientType.TO屬性表示接收者的類型為TO
            mailMessage.setRecipient(Message.RecipientType.TO, to);
            // 設置郵件消息的主題
            mailMessage.setSubject(mailInfo.getSubject());
            // 設置郵件消息發送的時間
            mailMessage.setSentDate(new Date());
            // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象
            Multipart mainPart = new MimeMultipart();
            // 創建一個包含HTML內容的MimeBodyPart
            BodyPart html = new MimeBodyPart();
            // 設置HTML內容
            html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
            mainPart.addBodyPart(html);
            // 將MiniMultipart對象設置為郵件內容
            mailMessage.setContent(mainPart);
            // 發送郵件
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }


    /**
     * 發送帶附件的郵件
     * @param info
     * @return
     */
    public boolean sendFileMail(MailInfo info, File file){
        Message attachmentMail = createAttachmentMail(info,file);
        try {
            Transport.send(attachmentMail);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 創建帶有附件的郵件
     * @return
     */
    private Message createAttachmentMail(final MailInfo info, File file) {
        //創建郵件
        MimeMessage message = null;
        Properties pro = info.getProperties();
        try {

            Session sendMailSession = Session.getInstance(pro, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(info.getUserName(),info.getPassword());
                }
            });

            message = new MimeMessage(sendMailSession);
            // 設置郵件的基本信息
            //創建郵件發送者地址
            Address from = new InternetAddress(info.getFromAddress());
            //設置郵件消息的發送者
            message.setFrom(from);
            //創建郵件的接受者地址,並設置到郵件消息中
            Address to = new InternetAddress(info.getToAddress());
            //設置郵件消息的接受者, Message.RecipientType.TO屬性表示接收者的類型為TO
            message.setRecipient(Message.RecipientType.TO, to);
            //郵件標題
            message.setSubject(info.getSubject());

            // 創建郵件正文,為了避免郵件正文中文亂碼問題,需要使用CharSet=UTF-8指明字符編碼
            MimeBodyPart text = new MimeBodyPart();
            text.setContent(info.getContent(), "text/html;charset=UTF-8");

            // 創建容器描述數據關系
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(text);
            // 創建郵件附件
            MimeBodyPart attach = new MimeBodyPart();

            FileDataSource ds = new FileDataSource(file);
            DataHandler dh = new DataHandler(ds);
            attach.setDataHandler(dh);
            attach.setFileName(MimeUtility.encodeText(dh.getName()));
            mp.addBodyPart(attach);
            mp.setSubType("mixed");
            message.setContent(mp);
            message.saveChanges();

        } catch (Exception e) {
            Log.e("TAG", "創建帶附件的郵件失敗");
            e.printStackTrace();
        }
        // 返回生成的郵件
        return message;
    }
}

  

第三步、發送郵件

這里舉例發送文本郵件和帶附件的郵件

public class MainActivity extends AppCompatActivity {
 
    private EditText editText;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.toAddEt);
    }
 
 
    public void senTextMail(View view) {
        SendMailUtil.send(editText.getText().toString());
    }
 
    public void sendFileMail(View view) {
 
        File file = new File(Environment.getExternalStorageDirectory()+File.separator+"test.txt");
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            String str = "hello world";
            byte[] data = str.getBytes();
            os.write(data);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if (os != null)os.close();
            } catch (IOException e) {
            }
        }
        SendMailUtil.send(file,editText.getText().toString());
    }
}

  下面是發送郵件的SendMailUtil

package com.chuanye.maidian.mail;

import android.support.annotation.NonNull;

import java.io.File;

public class SendMailUtil {
    //qq
    //private static final String HOST = "smtp.qq.com";
    //private static final String PORT = "587";
    //private static final String FROM_ADD = "changyiqiang666@163.com";
    //private static final String FROM_PSW = "qwertyuiop123456";

//    //163
    private static final String HOST = "smtp.163.com";
    private static final String PORT = "25"; //或者465  994

    //private static final String HOST = "pop.163.com";
    //private static final String PORT = "995"; //或者465  994
    private static final String FROM_ADD = "changyiqiang666@163.com";
    private static final String FROM_PSW = "qwertyuiop123456";//qwertyuiop123456
////    private static final String TO_ADD = "2584770373@qq.com";


    public static void send(final File file, String toAdd){
        final MailInfo mailInfo = creatMail(toAdd);
        final MailSender sms = new MailSender();
        new Thread(new Runnable() {
            @Override
            public void run() {
                sms.sendFileMail(mailInfo,file);
            }
        }).start();
    }


    public static void send(String toAdd){
        final MailInfo mailInfo = creatMail(toAdd);
        final MailSender sms = new MailSender();
        new Thread(new Runnable() {
            @Override
            public void run() {
                sms.sendTextMail(mailInfo);
            }
        }).start();
    }

    @NonNull
    private static MailInfo creatMail(String toAdd) {
        final MailInfo mailInfo = new MailInfo();
        mailInfo.setMailServerHost(HOST);// 發送郵件的服務器的IP
        mailInfo.setMailServerPort(PORT);// 發送郵件的服務器的端口
        mailInfo.setValidate(true);// 是否需要身份驗證
        mailInfo.setUserName(FROM_ADD); // 你的郵箱地址 // 登陸郵件發送服務器的用戶名
        mailInfo.setPassword(FROM_PSW);// 您的郵箱密碼 登陸郵件發送服務器的密碼
        mailInfo.setFromAddress(FROM_ADD); // 發送的郵箱 // 郵件發送者的地址
        mailInfo.setToAddress(toAdd); // 發到哪個郵件去
        mailInfo.setSubject("Hello"); // 郵件主題
        mailInfo.setContent("Android 測試"); // 郵件文本
        return mailInfo;
    }
}

  特別注意:一定要打開郵箱POP3/IMAP/SMTP服務,不然認證會失敗

 

需要把SendMailUtil 下的FROM_ADD,FROM_PSW配置成你自己的賬號和授權碼

 private static final String FROM_ADD = "changyiqiang666@163.com";
    private static final String FROM_PSW = "qwertyuiop123456";//qwertyuiop123456

  另外端口我設置為了25

private static final String PORT = "25"; //或者465  994

 最后權限

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

  

 

不然會報如下錯誤

07-19 11:02:09.724 31125-32494/com.chuanye.maidian I/System.out: [socket] connection smtp.163.com/220.181.12.13:994;LocalPort=58772(0)
07-19 11:02:29.790 31125-32494/com.chuanye.maidian W/System.err: javax.mail.MessagingException: Could not connect to SMTP host: smtp.163.com, port: 994, response: -1
07-19 11:02:29.790 31125-32494/com.chuanye.maidian W/System.err:     at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1379)
07-19 11:02:29.790 31125-32494/com.chuanye.maidian W/System.err:     at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
07-19 11:02:29.790 31125-32494/com.chuanye.maidian W/System.err:     at javax.mail.Service.connect(Service.java:310)
07-19 11:02:29.790 31125-32494/com.chuanye.maidian W/System.err:     at javax.mail.Service.connect(Service.java:169)
07-19 11:02:29.790 31125-32494/com.chuanye.maidian W/System.err:     at javax.mail.Service.connect(Service.java:118)
07-19 11:02:29.790 31125-32494/com.chuanye.maidian W/System.err:     at javax.mail.Transport.send0(Transport.java:188)
07-19 11:02:29.790 31125-32494/com.chuanye.maidian W/System.err:     at javax.mail.Transport.send(Transport.java:118)
07-19 11:02:29.790 31125-32494/com.chuanye.maidian W/System.err:     at com.chuanye.maidian.mail.MailSender.sendTextMail(MailSender.java:69)
07-19 11:02:29.790 31125-32494/com.chuanye.maidian W/System.err:     at com.chuanye.maidian.mail.SendMailUtil$2.run(SendMailUtil.java:43)
07-19 11:02:29.790 31125-32494/com.chuanye.maidian W/System.err:     at java.lang.Thread.run(Thread.java:818)
07-19 11:02:39.315 31125-31125/com.chuanye.maidian W/IInputConnectionWrapper: clearMetaKeyStates on inactive InputConnection
07-19 11:02:39.903 31125-31125/com.chuanye.maidian W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
07-19 11:02:39.904 31125-31125/com.chuanye.maidian W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
07-19 11:02:39.906 31125-31125/com.chuanye.maidian W/IInputConnectionWrapper: clearMetaKeyStates on inactive InputConnection

  完成

參考於:https://blog.csdn.net/qiujiaxin050/article/details/81081651

https://www.jianshu.com/p/f940ebcae899

感謝

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM