http://llshenglin.iteye.com/blog/1030505
android 邮件开发(javax.mail)
文章分类:Java编程
以前在csdn上发贴求助android邮件开发的开发,后来问题自己解决了。有很多网友遇到了同样的问题,发邮件问我都没及时回复。在这里我把封存装的email源代码贴出来,和大家分享。android开发邮件需要添加三个扩展包:mail.jar,additional.jar,和activation.jar。直接用java开发,则只需前面两个包。两种不同的开发方式,包的版本是不同的。
封装了一个SMailSender 类,类是Runnable的实现,也就是邮件功能可作为一个线程在后台运行。SMailSender类目前只支持gmail、126和163三种邮箱,如果要支持其他邮箱,可根据邮箱的协议类型进行相应的扩展。
SMailSender.java
- package com.jia.test;
- import java.util.Properties;
- import javax.activation.DataHandler;
- import javax.activation.FileDataSource;
- import javax.mail.BodyPart;
- import javax.mail.Message;
- import javax.mail.Multipart;
- 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 android.util.Log;
- public class SMailSender implements Runnable {
- private final String Tag = "SMailSender";
- private String mSmtp_host;
- private String mFrom_userName;
- private String mFrom_passWord;
- private String mShow_name = "Jiahe";
- private MimeMessage mMimeMsg; // 要发送的email信息
- private Session mSession;
- private Multipart mp; // 存放邮件的title 内容和附件
- private String mSubject;
- private String mContent;
- private String mToId = null;
- private String mCcId = null;
- private String mBccId = null;
- private String mFilePath = null;
- private final int NONE = 0;
- private final int CONNECTING = 1;
- private final int CONNECTED = 2;
- private final int SENDING = 3;
- private final int SENDED = 4;
- private int mState;
- public enum MailType {
- TYPE_GMAIL, TYPE_126, TYPE_163, TYPE_QQ;
- }
- private MailType mailType;
- //private Properties props;
- /**
- * 构造函数
- * @param hostName
- */
- public SMailSender(){
- // mSmtp_host = "smtp.gmail.com";
- mp = new MimeMultipart();
- }
- public SMailSender(String hostName){
- // mSmtp_host = hostName;
- mp = new MimeMultipart();
- }
- /**
- * 设置发件人的用户名和密码
- * 目前只支持gmail、126、163邮箱
- * @param _userName
- * @param _password
- */
- public boolean setAuthor(String _userName, String _password){
- mFrom_userName = _userName;
- mFrom_passWord = _password;
- return setHost(mFrom_userName); //设置邮箱类型
- }
- /**
- * 设置邮件主题
- * @param subject
- */
- public void setSubject(String subject){
- if(subject!= null)
- mSubject = subject;
- }
- /**
- * 设置邮件内容
- * @param content
- */
- public void setContent(String content){
- if(content != null)
- mContent = content;
- }
- /**
- * 设置收件人,收件人之间用";"隔开
- * @param to
- * @return
- */
- public void setTo(String toId){
- mToId = toId;
- }
- /**
- * 设置邮件抄送人,抄送人之间用";"隔开
- * @param copyto
- * @return
- */
- public void setCc(String ccId){
- mCcId = ccId;
- }
- /**
- * 设置暗抄送人,暗抄送人之间用";"隔开
- * @param bcopyto
- * @return
- */
- public void setBcc(String bccId){
- mBccId = bccId;
- }
- public void setShowName(String name){
- mShow_name = name;
- }
- /**
- * 设置附件路径,路径之间用";"隔开
- * @param path
- */
- public void addFileAffix(String path){
- mFilePath = path;
- }
- public int getMailState(){
- return mState;
- }
- @Override
- public void run() {
- executeMailandSend();
- }
- private boolean setSendToMsg(String to) {
- if (to.equals("") || to == null) {
- return false;
- }
- try {
- String sendto[];
- sendto = to.split(";");
- for (int i = 0; i < sendto.length; i++) {
- mMimeMsg.addRecipients(Message.RecipientType.TO,
- InternetAddress.parse(sendto[i]));
- }
- return true;
- } catch (Exception e) {
- return false;
- }
- }
- private boolean setCopyToMsg(String copyto) {
- if (copyto.equals("") || copyto == null) {
- return false;
- }
- try {
- String copy[];
- copy = copyto.split(";");
- for (int i = 0; i < copy.length; i++) {
- mMimeMsg.addRecipients(Message.RecipientType.CC,
- InternetAddress.parse(copy[i]));
- }
- return true;
- } catch (Exception e) {
- return false;
- }
- }
- private boolean setBCopyToMsg(String bcopyto){
- if (bcopyto.equals("") || bcopyto == null) {
- return false;
- }
- try {
- String bcopy[];
- bcopy = bcopyto.split(";");
- for (int i = 0; i < bcopy.length; i++) {
- mMimeMsg.addRecipients(Message.RecipientType.BCC,
- InternetAddress.parse(bcopy[i]));
- }
- return true;
- } catch (Exception e) {
- return true;
- }
- }
- private boolean setContentMp(String conMp){
- try {
- BodyPart bp = new MimeBodyPart();
- bp.setContent(
- "<meta http-equiv=Context-Type context=text/html;charset=gb2312>"
- + conMp, "text/html;charset=GB2312");
- mp.addBodyPart(bp);
- return true;
- } catch (Exception e) {
- System.out.println("Set context Faild! " + e);
- return false;
- }
- }
- private boolean addFile(String filePath){
- // System.out.println("add affix..");
- if (filePath.equals("") || filePath == null) {
- return false;
- }
- String file[];
- file = filePath.split(";");
- // System.out.println("you have " + file.length + " affix!");
- try {
- for (int i = 0; i < file.length; i++) {
- BodyPart bp = new MimeBodyPart();
- FileDataSource fileds = new FileDataSource(file[i]);
- bp.setDataHandler(new DataHandler(fileds));
- bp.setFileName(fileds.getName());
- mp.addBodyPart(bp);
- }
- return true;
- } catch (Exception e) {
- Log.d(Tag, "add affix: " + filePath + "--faild!" + e);
- System.err.println("add affix: " + filePath + "--faild!" + e);
- return false;
- }
- }
- private boolean setHost(String mailAddress){
- if(mailAddress.contains("@gmail.")){
- mSmtp_host = "smtp.gmail.com";
- mailType = MailType.TYPE_GMAIL;
- return true;
- }
- if(mailAddress.contains("@126.")){
- mSmtp_host = "smtp.126.com";
- mailType = MailType.TYPE_126;
- return true;
- }
- if(mailAddress.contains("@163.")){
- mSmtp_host = "smtp.163.com";
- mailType = MailType.TYPE_163;
- return true;
- }
- else
- return false;
- /* if(mailAddress.contains("@qq.")){
- mSmtp_host = "smtp.qq.com";
- mailType = MailType.TYPE_QQ;
- }*/
- }
- private void executeMailandSend() {
- try {
- mState = NONE;
- Properties props = System.getProperties();
- props = System.getProperties();
- if(mailType == MailType.TYPE_GMAIL){ //如果为gmail邮箱,需要设置下两项
- props.put("mail.smtp.starttls.enable", "true");
- props.put("mail.smtp.port", "587"); // gmail smtp port 587 / 465
- }
- props.put("mail.smtp.host", mSmtp_host);
- props.put("mail.smtp.user", mFrom_userName);
- props.put("mail.smtp.password", mFrom_passWord);
- props.put("mail.smtp.auth", "true");
- mSession = Session.getDefaultInstance(props, null);
- mSession.setDebug(false);
- mMimeMsg = new MimeMessage(mSession);
- mMimeMsg.setFrom(new InternetAddress(mFrom_userName));
- //mMimeMsg.setContent(mContent, "text/html;charset=utf-8");
- if(mToId != null)
- setSendToMsg(mToId);
- if(mCcId != null)
- setCopyToMsg(mCcId);
- if(mBccId != null)
- setBCopyToMsg(mBccId);
- if(mSubject != null){
- mMimeMsg.setSubject(mSubject);
- }
- if(mShow_name != null){
- mMimeMsg.setFrom(new InternetAddress(mShow_name + "<"
- + mFrom_userName + ">"));
- }
- if(mContent != null){
- setContentMp(mContent);
- mMimeMsg.setContent(mp);
- }
- if(mFilePath != null){
- addFile(mFilePath);
- }
- System.out.println(mMimeMsg.getAllRecipients().toString());
- Transport transport = mSession.getTransport("smtp");
- System.out.println("connecting...");
- mState = CONNECTING;
- transport.connect(mSmtp_host, mFrom_userName, mFrom_passWord);
- mState = CONNECTED;
- Log.i(Tag, "Connected to " + mFrom_userName + " succuss");
- System.out.println("sending...");
- mState = SENDING;
- transport.sendMessage(mMimeMsg, mMimeMsg.getAllRecipients());
- mState = SENDED;
- transport.close();
- Log.i(Tag, "Send a mail to " + mToId);
- System.out.println("send an email to " + mToId + " success");
- }
- catch (Exception e) {
- System.out.println("failure! ");
- Log.d(Tag, " failure! ", e);
- e.printStackTrace();
- }
- }
- }
上面的类调用比较简单,再给一个使用的实例MailBackground.java:
- package com.jia.test;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MailBackground extends Activity{
- private EditText mEditText_1;
- private EditText mEditText_2;
- private EditText mEditText_3;
- private EditText mEditText_4;
- // private EditText mEditText_5;
- private Button mButton;
- private TextView mTextView;
- SMailSender mail;
- private int mPreState;
- private int mRealState;
- private Thread thread_mail;
- @Override
- public void onBackPressed() {
- super.onBackPressed();
- finish();
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.mail_layout);
- mEditText_1 = (EditText)findViewById(R.id.email_num_to);
- mEditText_1.setText("sanditest01@126.com");
- mEditText_2 = (EditText)findViewById(R.id.email_num_cc);
- mEditText_2.setText("sanditest02@163.com");
- mEditText_3 = (EditText)findViewById(R.id.email_subject);
- mEditText_3.setText("hello, this is a test email");
- mEditText_4 = (EditText)findViewById(R.id.email_text);
- //mEditText_4.setText("您好:/n this is a test email, you don't need to reply to, thanks for your help!");
- mEditText_4.setText("this is a test email, you don't need");
- // mEditText_5 = (EditText)findViewById(R.id.email_file);
- // mEditText_5.setText("");
- mTextView = (TextView)findViewById(R.id.email_file_view);
- mButton = (Button)findViewById(R.id.button_sendEmail);
- mButton.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View v) {
- System.out.println("send clicked");
- String to = mEditText_1.getText().toString();
- String cc = mEditText_2.getText().toString();
- String subject = mEditText_3.getText().toString();
- String content = mEditText_4.getText().toString();
- // String filePath = mEditText_5.getText().toString();
- mail = new SMailSender();
- // mail.setAuthor("sanditest01@126.com", "sanditest");
- mail.setAuthor("sanditest01@gmail.com", "sanditest");
- // mail.setAuthor("sanditest02@163.com", "sanditest");
- mail.setShowName("Sandi");
- mail.setTo(to); //密码:sanditest
- mail.setCc(cc);
- mail.setSubject(subject);
- mail.setContent(content);
- mRealState = mPreState = 0;
- thread_mail = new Thread(mail);
- new Thread(r);
- thread_mail.start(); //启动发送线程
- //thread_state.start(); //启动状态监视线程
- Monitor();
- }
- });
- }
- Runnable r = new Runnable(){
- public void run() {
- while(true){
- try {
- Thread.sleep(100);
- mRealState = mail.getMailState();
- System.out.println("mRealState = " + mRealState);
- if(mRealState == mPreState)
- continue;
- if(1 == mRealState){
- mPreState = mRealState;
- System.out.println("Toast mRealState2 = " + mRealState);
- }
- if(2 == mRealState){
- mPreState = mRealState;
- }
- if(3 == mRealState){
- mPreState = mRealState;
- }
- if(4 == mRealState){ //邮件发送成功,线程退出
- mPreState = mRealState;
- break;
- }
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- };
- protected void Monitor() {
- while (true) {
- try {
- Thread.sleep(10);
- mRealState = mail.getMailState();
- //System.out.println("mRealState = " + mRealState);
- if (mRealState == mPreState)
- continue;
- if (1 == mRealState) {
- mPreState = mRealState;
- mTextView.setText("Connecting...");
- System.out.println("Toast mRealState1 = " + mRealState);
- // setTitle("Connecting...");
- Toast.makeText(MailBackground.this, "Connecting",
- Toast.LENGTH_SHORT).show();
- System.out.println("Toast mRealState2 = " + mRealState);
- }
- if (2 == mRealState) {
- mPreState = mRealState;
- mTextView.setText("Connecting success");
- // setTitle("Connected success");
- Toast.makeText(getApplicationContext(), "Connecting",
- Toast.LENGTH_SHORT).show();
- }
- if (3 == mRealState) {
- mPreState = mRealState;
- mTextView.setText("Sending");
- Toast.makeText(getApplicationContext(), "Sending",
- Toast.LENGTH_SHORT).show();
- }
- if (4 == mRealState) { // 邮件发送成功,线程退出
- mPreState = mRealState;
- mTextView.setText("Send email success");
- Toast.makeText(getApplicationContext(), "Send success!",
- Toast.LENGTH_SHORT).show();
- break;
- }
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }