您的位置:首页 > 移动开发 > Android开发

android 发送邮件(android自带email和javamail)均可发送带有多个附件

2013-10-17 14:40 519 查看
1.android自带的mail

package com.email.sendmail;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.email.R;
import com.email.R.id;
import com.email.R.layout;
import com.email.R.string;
import com.email.selectfile.FileChooserActivity;

/**
* 发送邮件,可以发送带附件的邮件
* */
public class SendEmailActivity extends Activity implements OnClickListener {

private EditText address;
private EditText details;
private EditText title;
private Button send;
private Button addAttach;
private Button reback;
private Intent fileChooserIntent;
private ListView lv_filePath;
private SimpleAdapter adapter;
private List<Map<String, String>> list;

private static final int REQUEST_CODE = 1; // 请求码
public static final String EXTRA_FILE_CHOOSER = "file_chooser";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_sendemail);
init();
}

private void init() {
// TODO Auto-generated method stub
address = (EditText) findViewById(R.id.et_sendemail_address);
details = (EditText) findViewById(R.id.et_sendemail_details);
title = (EditText) findViewById(R.id.et_sendemail_title);
lv_filePath = (ListView) findViewById(R.id.lv_sendmail_filepath);
lv_filePath.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
showDeleteAttachDialog(arg2);
return true;
}
});
addAttach = (Button) findViewById(R.id.bu_sendemail_addmuti);
addAttach.setOnClickListener(this);
send = (Button) findViewById(R.id.bu_sendemail_send);
send.setOnClickListener(this);
reback = (Button) findViewById(R.id.bu_sendmail_reback);
reback.setOnClickListener(this);

fileChooserIntent = new Intent(this, FileChooserActivity.class);

list = new ArrayList<Map<String, String>>();
}

private void showDeleteAttachDialog(int position) {
final int location = position;
AlertDialog dialog = new AlertDialog.Builder(SendEmailActivity.this)
.setTitle("是否确定删除该附件")
.setPositiveButton("删除", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
list.remove(location);
lv_filePath.setAdapter(adapter);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
dialog.cancel();
}
}).create();
dialog.show();
}

private boolean validate(String reciver, String mySubject, String mybody) {
if (reciver.isEmpty()) {
toast("收件人邮箱地址不能为空");
return false;
}
if (mySubject.isEmpty()) {
toast("邮件标题不能为空");
return false;
}
if (mybody.isEmpty()) {
toast("邮件内容不能为空");
return false;
}
return true;
}

private void sendMailByJavaMail() {
// String reciver = address.getText().toString();
// String mySubject = title.getText().toString();
// String mybody = details.getText().toString();

String reciver = "abcw111222@163.com";
String mybody = "elena_and_demon";
String mySubject = "happy_ending";

if (validate(reciver, mySubject, mybody)) {
if (isEmail(reciver)) {
if(list.size()>0){//判断邮件中是否含有附件,含有附件时用此方法发送邮件
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
// 发送多个附件时,需要用ACTION_SEND_MULTIPLE,一般情况用ACTION_SEND
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { reciver });
intent.putExtra(Intent.EXTRA_SUBJECT, mySubject);
intent.putExtra(Intent.EXTRA_TEXT, mybody);
if (list.size() > 0) {
ArrayList<Uri> uri = new ArrayList<Uri>();
for (int i = 0; i < list.size(); i++) {
String file_path = list.get(i).get("filepath")
.toString();
if (!file_path.isEmpty()) {
File file = new File(file_path); // 附件文件地址
if (file.getName().endsWith(".gz")) {
intent.setType("application/x-gzip"); // 如果是gz使用gzip的mime
} else if (file.getName().endsWith(".txt")) {
intent.setType("text/plain"); // 纯文本则用text/plain的mime
} else {
intent.setType("application/octet-stream"); // 其他的均使用流当做二进制数据来发送
}
uri.add(Uri.fromFile(file));
}
}
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uri);
// 添加附件,附件为file对象,多个附件时用这个,如果只有一个附件,可以直接putextra(Intent.EXTRA_STREAM,Uri);
}
startActivity(intent); // 调用系统的mail客户端进行发送。
}else{//发送不带附件的邮件
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:" + reciver));
intent.putExtra(Intent.EXTRA_SUBJECT, mySubject);
intent.putExtra(Intent.EXTRA_TEXT, mybody);
startActivity(intent); // 调用系统的mail客户端进行发送。
}
}
}
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bu_sendemail_send:
sendMailByJavaMail();
break;
case R.id.bu_sendemail_addmuti://获取附件在sdcard中的位置。取得位置的详细代码见下一篇文章。
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED))
startActivityForResult(fileChooserIntent, REQUEST_CODE);
else
toast(getText(R.string.sdcard_unmonted_hint));
break;
case R.id.bu_sendmail_reback:
finish();
break;
default:
break;
}
}

// 判断email格式是否正确
public boolean isEmail(String email) {
String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(email);
return m.matches();
}

private void toast(CharSequence hint) {
Toast.makeText(this, hint, Toast.LENGTH_SHORT).show();
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (resultCode == RESULT_CANCELED) {
toast(getText(R.string.open_file_none));
return;
}
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
// 获取路径名
String filePath = data.getStringExtra(EXTRA_FILE_CHOOSER);
if (filePath != null) {
Map<String, String> map = new HashMap<String, String>();
map.put("filepath", filePath);
list.add(map);
adapter = new SimpleAdapter(SendEmailActivity.this, list,
R.layout.item_sendemailattath,
new String[] { "filepath" },
new int[] { R.id.tv_item_sendemailattath });
lv_filePath.setAdapter(adapter);
} else
toast("打开文件失败");
}
}

}


2.javamail发送邮件

package com.email.sendjm;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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;

public class MailSendJavaMail extends Authenticator{

private String user;
private String password;
private Session session;

static {
Security.addProvider(new JSSEProvider());
}
/**
* mailhost:host
* sslFlag:是否加密
* */
public MailSendJavaMail(String mailhost, String user, String password,
boolean sslFlag) {
this.user = user;
this.password = password;

Properties props = new Properties();
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
if (sslFlag) {
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
} else {
props.put("mail.smtp.port", "25");//发送邮件的端口为25
}
props.setProperty("mail.smtp.quitwait", "false");

session = Session.getDefaultInstance(props, this);
}

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
/**
* @subject:邮箱主题
* @body:邮件具体的内容,不包含附件
* @sender:发送者
* @recipients:接收者
* */

public synchronized void sendMail(String subject, String body,
String sender, String recipients) throws Exception {
Vector<String> file = new Vector<String>();//用于保存发送附件的文件名的集合
file.addElement(File.separator + "mnt" + File.separator + "sdcard" + File.separator + "25465.txt" );
file.addElement(File.separator + "mnt" + File.separator + "sdcard" + File.separator + "图片1.jpg");
MimeMessage message = new MimeMessage(session);
message.setSender(new InternetAddress(sender));
message.setSubject(subject);

Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
if(!file.isEmpty()){
Enumeration<String> efile = file.elements();
while(efile.hasMoreElements()){
mbp = new MimeBodyPart();
String filename = efile.nextElement().toString();
FileDataSource fds = new FileDataSource(filename);
mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(body.getBytes(),"text/plain")));
mbp.setFileName(fds.getName());
mp.addBodyPart(mbp);
}
file.removeAllElements();
}
message.setContent(mp);

message.setFrom(new InternetAddress(sender));
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(
recipients));
Transport.send(message);
}

public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;

public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}

public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}

public void setType(String type) {
this.type = type;
}

public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}

public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}

public String getName() {
return "ByteArrayDataSource";
}

public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}

}
============================================================================================
 package com.email.sendjm;

import java.security.AccessController;
import java.security.Provider;

public class JSSEProvider extends Provider{
    

    private static final long serialVersionUID = 1L;

    public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController
                .doPrivileged(new java.security.PrivilegedAction<Void>() {
                    public Void run() {
                        put("SSLContext.TLS",
                                "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                        put("Alg.Alias.SSLContext.TLSv1", "TLS");
                        put("KeyManagerFactory.X509",
                                "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                        put("TrustManagerFactory.X509",
                                "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                        return null;
                    }
                });
    }

}

=======================================================================================================
在主函数中调用上述方法发送邮件
//                MailSendJavaMail ss = new MailSendJavaMail("smtp.163.com", "abcw111222@163.com", "123456w", false);//javamail发送邮件
//                try {
//                    ss.sendMail("aaaa", "ddd", "邮箱名@163.com", "邮箱名@qq.com");
//                } catch (Exception e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息