欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android快速实现发送邮件实例

程序员文章站 2022-06-12 13:32:12
前言 现在一般很少有用android原生app发送邮件的需求,但是前段时间公司项目需要在android app 内部发送邮件,于是就在网上收集资料并整理了一个demo。虽...

前言

现在一般很少有用android原生app发送邮件的需求,但是前段时间公司项目需要在android app 内部发送邮件,于是就在网上收集资料并整理了一个demo。虽然最后这个需求被减掉了,但是我这里还是把demo的内容给大家分享一下。

第一步、导入第三方jar包

android实现发送邮件,首先需要依赖additional.jar、mail.jar和activation.jar这3个jar包。google提供了下载地址: 。下载后添加到依赖(这里我就不详细说明了)。

第二步、创建相关类

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。