上一篇写了一个java发送邮件的工具,原本想用到Android中,但是java工程中的jar包与Android中使用的jar是不一样的。用法也有所不同,其实也一样,稍微有点变化。
Android中使用的两个个jar包 activation.jar 、mail.jar 可到https://www.mvnjar.com/com.sun.mail/list.html中下载两个jar包,或者使用仓库地址。
比较懒得我就不喜欢定义什么对象类来控制消息的发送了,之间将消息塞进去很实在。
直接看代码:
package com.sai.library.email;
import android.util.Log;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
public class SendEmail {
public interface Callback {
void success(String s);
void error(String s, Exception e);
}
public static final String DATA_TYPE_HTML = "text/html;charset=utf-8";
private Callback callback; //信息回调接口
private Properties properties;//系统属性对象
private String mailAccount; //发送邮箱地址
private String mailPassword; //验证密码
private Session session; //邮件会话对象
private String myNickName; //昵称,发送时自己的昵称
private boolean debug = false;//debug模式
private boolean isSaveEmail = false;
private String pathName = "exc.eml";//邮件保存时的
public SendEmail(String mailAccount, String mailPassword) {
this.mailAccount = mailAccount;
this.mailPassword = mailPassword;
}
public SendEmail setSaveEmail(String pathName) {
isSaveEmail = true;
this.pathName = pathName;
return this;
}
private List<String> recipientT0List = new ArrayList<>();//收件地址
private List<String> recipientCCList = new ArrayList<>();//密送地址
private List<String> recipientBCCList = new ArrayList<>();//抄送地址
private List<String> filePath = new ArrayList<>();//附件
public SendEmail setDebug(boolean sessionDebug) {
debug = sessionDebug;
return this;
}
/*** 设置多人收件人地址 */
public SendEmail addRecipientT0(String address) {
recipientT0List.add(address);
return this;
}
public SendEmail addRecipientCC(String address) {
recipientCCList.add(address);
return this;
}
public SendEmail addRecipientBCC(String address) {
recipientBCCList.add(address);
return this;
}
public SendEmail addRecipientT0(List<String> address) {
recipientT0List.addAll(address);
return this;
}
public SendEmail addRecipientCC(List<String> address) {
recipientCCList.addAll(address);
return this;
}
public SendEmail addRecipientBCC(