中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android快速實現發送郵件實例

發布時間:2020-10-13 05:07:04 來源:腳本之家 閱讀:199 作者:Teprinciple 欄目:移動開發

前言

現在一般很少有用Android原生app發送郵件的需求,但是前段時間公司項目需要在Android app 內部發送郵件,于是就在網上收集資料并整理了一個Demo。雖然最后這個需求被減掉了,但是我這里還是把Demo的內容給大家分享一下。

第一步、導入第三方jar包

Android實現發送郵件,首先需要依賴additional.jar、mail.jar和activation.jar這3個jar包。Google提供了下載地址:https://code.google.com/archive/p/javamail-android/downloads 。下載后添加到依賴(這里我就不詳細說明了)。

第二步、創建相關類

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

package com.shidian.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.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;
  }
}

2、創建認證類MyAuthenticator

package com.shidian.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.shidian.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;
  }
}

第三步、發送郵件

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

package teprinciple.yang.sendmaildemo;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.shidian.mail.SendMailUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

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.shidian.mail;

import android.support.annotation.NonNull;

import java.io.File;

/**
 * Created by Administrator on 2017/4/10.
 */

public class SendMailUtil {
  //qq
  private static final String HOST = "smtp.qq.com";
  private static final String PORT = "587";
  private static final String FROM_ADD = "teprinciple@foxmail.com";
  private static final String FROM_PSW = "lfrlpganzjrwbeci";

//  //163
//  private static final String HOST = "smtp.163.com";
//  private static final String PORT = "465"; //或者465 994
//  private static final String FROM_ADD = "teprinciple@163.com";
//  private static final String FROM_PSW = "teprinciple163";
////  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);
    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服務,不然認證會失敗

Android快速實現發送郵件實例

項目地址:https://github.com/teprinciple/SendMailDemo

demo下載地址:SendMailDemo_jb51.rar

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

奈曼旗| 明星| 呈贡县| 黄冈市| 丹东市| 阿瓦提县| 从江县| 大丰市| 新民市| 望谟县| 松原市| 仙桃市| 云和县| 东明县| 双桥区| 湟中县| 壶关县| 雅江县| 措美县| 开鲁县| 湖口县| 洛阳市| 砀山县| 安阳市| 巫溪县| 成武县| 丰台区| 周至县| 湖州市| 西林县| 乡宁县| 长白| 木兰县| 嵊泗县| 年辖:市辖区| 武冈市| 抚州市| 大姚县| 临湘市| 宜川县| 襄垣县|