項目中有些關鍵日誌需要從客戶手中拿到,爲了方便的收集日誌在客戶端中加入郵件發送功能(雖然使用分享功能也能發送郵件,前提需要客戶登錄手機的郵箱才行,比較麻煩,而且還進入頁面,用戶體驗不太好)。
主要實現了發送郵件,抄送,發送附件功能
先看一下效果圖:
涉及到3個jar以及封裝的接口
JEmailHelper.java
package jwzhangjie.com.javaemail;
import android.os.AsyncTask;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.Authenticator;
import javax.mail.Message;
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;
/**
* Created by zhangjie on 15/8/31.
*/
public class JEmailHelper {
private int port = 553; //smtp協議使用的端口
private String host = "smtp.163.com"; // 發件人郵件服務器
private String user = "*******@163.com"; // 使用者賬號
private String password = "********"; //使用者密碼
private List<String> emailTos;
private List<String> emailCCs;
private String subject;
private String body;
private List<String> paths;
enum SendStatus {
SENDING, UNDO, SENDOK, SENDFAIL
}
;
private SendStatus sendStatus;
public interface JieEmailInfterface {
void startSend();
void SendStatus(SendStatus sendStatus);
}
private JieEmailInfterface jieEmailInfterface;
public void setJieEmailInfterface(JieEmailInfterface jieEmailInfterface) {
this.jieEmailInfterface = jieEmailInfterface;
}
public JEmailHelper() {
sendStatus = SendStatus.UNDO;
}
//構造發送郵件帳戶的服務器,端口,帳戶,密碼
public JEmailHelper(String host, int port, String user, String password) {
this.port = port;
this.user = user;
this.password = password;
this.host = host;
sendStatus = SendStatus.UNDO;
}
/**
* @param emailTos 主要接收人的電子郵箱列表
* @param emailCCs 抄送人的電子郵箱列表
* @param subject 郵件標題
* @param body 正文內容
* @param paths 發送的附件路徑集合
*/
public void setParams(List<String> emailTos, List<String> emailCCs, String subject, String body,
List<String> paths) {
this.emailTos = emailTos;
this.emailCCs = emailCCs;
this.subject = subject;
this.body = body;
this.paths = paths;
}
public void sendEmail() {
new JieAsynTask().execute();
}
private void sendEmailBg() throws Exception {
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");//true一定要加引號
properties.put("mail.transport.protocol", "smtp");
JieAuthenticator jieAuth = new JieAuthenticator(user, password);
Session session = Session.getInstance(properties, jieAuth);
//創建一個消息
MimeMessage msg = new MimeMessage(session);
//設置發送人
msg.setFrom(new InternetAddress(user));
//設置主要接收人
if (emailTos != null && !emailTos.isEmpty()) {
int size = emailTos.size();
InternetAddress[] addresses = new InternetAddress[size];
for (int i = 0; i < size; i++) {
addresses[i] = new InternetAddress(emailTos.get(i));
}
msg.setRecipients(Message.RecipientType.TO, addresses);
}
//設置抄送人的電子郵件
if (emailCCs != null && !emailCCs.isEmpty()) {
int size = emailCCs.size();
InternetAddress[] addresses = new InternetAddress[size];
for (int i = 0; i < size; i++) {
addresses[i] = new InternetAddress(emailCCs.get(i));
}
msg.setRecipients(Message.RecipientType.CC, addresses);
}
msg.setSubject(subject);
//創建一個消息體
MimeBodyPart msgBodyPart = new MimeBodyPart();
msgBodyPart.setText(body);
//創建Multipart增加其他的parts
Multipart mp = new MimeMultipart();
mp.addBodyPart(msgBodyPart);
//創建文件附件
for (String path : paths) {
MimeBodyPart fileBodyPart = new MimeBodyPart();
fileBodyPart.attachFile(path);
mp.addBodyPart(fileBodyPart);
}
//增加Multipart到消息體中
msg.setContent(mp);
//設置日期
msg.setSentDate(new Date());
//設置附件格式
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
//發送消息
Transport.send(msg);
}
class JieAuthenticator extends Authenticator {
private String strUser;
private String strPwd;
public JieAuthenticator(String user, String password) {
this.strUser = user;
this.strPwd = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(strUser, strPwd);
}
}
class JieAsynTask extends AsyncTask<Void, Void, SendStatus> {
@Override
protected void onPreExecute() {
super.onPreExecute();
if (jieEmailInfterface != null) {
jieEmailInfterface.startSend();
}
}
@Override
protected void onPostExecute(SendStatus result) {
super.onPostExecute(result);
if (jieEmailInfterface != null) {
jieEmailInfterface.SendStatus(result);
}
sendStatus = SendStatus.UNDO;
}
@Override
protected SendStatus doInBackground(Void... params) {
try {
sendStatus = SendStatus.SENDING;
sendEmailBg();
sendStatus = SendStatus.SENDOK;
} catch (Exception e) {
e.printStackTrace();
sendStatus = SendStatus.SENDFAIL;
}
return sendStatus;
}
}
}
package jwzhangjie.com.javaemail;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class JavaEmailActivity extends Activity {
JEmailHelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_java_email);
helper = new JEmailHelper();
}
public void sendMail(View view) {
List<String> files = new ArrayList<String>();
files.add("/mnt/sdcard/test.txt");
List<String> toEmail = new ArrayList<String>();
toEmail.add("[email protected]");
List<String> ccEmail = new ArrayList<String>();
ccEmail.add("1067*****@qq.com");
ccEmail.add("352****@qq.com");
helper.setParams(toEmail, ccEmail, "Android發送測試郵件", "Dear All:這是一封測試郵件!", files);
helper.setJieEmailInfterface(new JEmailHelper.JieEmailInfterface() {
@Override
public void startSend() {
showInfo("開始發送郵件");
}
@Override
public void SendStatus(JEmailHelper.SendStatus sendStatus) {
switch (sendStatus) {
case SENDOK:
showInfo("發送郵件成功");
break;
case SENDFAIL:
showInfo("發送郵件失敗");
break;
case SENDING:
showInfo("郵件正在發送中,請稍後重試");
break;
}
}
});
helper.sendEmail();
}
public void showInfo(String msg){
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
}
三個jar的地址:http://pan.baidu.com/s/1bnbi7zp
備註:如果附件中有中文會亂碼,下面使用下面代碼替換上傳附件解決中文亂碼
//創建文件附件
for (String path : paths) {
MimeBodyPart fileBodyPart = new MimeBodyPart();
File file = new File(path);
fileBodyPart.attachFile(file);
fileBodyPart.setFileName(MimeUtility.encodeText(file.getName()));
mp.addBodyPart(fileBodyPart);
}