使用两种方式,Android 发送文件到指定邮箱(带多个附件)

第一种方法,调用系统的邮件软件来发送

众所周知在Android中调用其他程序进行相关处理,都是使用的Intent。当然,Email也不例外。

 在Android中,调用Email有三种类型的Intent:

 Intent.ACTION_SENDTO  无附件的发送

 Intent.ACTION_SEND  带附件的发送

 Intent.ACTION_SEND_MULTIPLE  带有多附件的发

 1、使用SENDTO发送

 Intent data=new Intent(Intent.ACTION_SENDTO);  
 data.setData(Uri.parse("mailto:455245521@qq.com"));  
 data.putExtra(Intent.EXTRA_SUBJECT, "这是标题");  
 data.putExtra(Intent.EXTRA_TEXT, "这是内容");  
 startActivity(data); 

  通过向Intent中putExtra来设定邮件的相关参数。

2、使用SEND发送

Intent intent = new Intent(Intent.ACTION_SEND);
String[] tos = { "fdafdafa@gmail.com" }; 
String[] ccs = { "gegeff@gmail.com" }; 
String[] bccs = {"fdafda@gmail.com"};
intent.putExtra(Intent.EXTRA_EMAIL, tos);
intent.putExtra(Intent.EXTRA_CC, ccs);
intent.putExtra(Intent.EXTRA_BCC, bccs);
intent.putExtra(Intent.EXTRA_TEXT, "body");
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
		
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/Chrysanthemum.jpg"));
intent.setType("image/*");
intent.setType("message/rfc882");
Intent.createChooser(intent, "Choose Email Client");
startActivity(intent);


很简单,发送邮件中,有收件者,抄送者,密送者。 也就是分别通过

     Intent.EXTRA_EMAIL,

     Intent.EXTRA_CC,

     Intent.EXTRA_BCC

  来进行putExtra来设定的

 
而单个附件的发送,则使用Intent.EXTRA_STREAM来设置附件的地址Uri。

3、使用SEND_MULTIPLE来进行多附件的发送

		Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
		String[] tos = { "wingfourever@gmail.com" }; 
		String[] ccs = { "tongyue@gmail.com" }; 
		intent.putExtra(Intent.EXTRA_EMAIL, tos);
		intent.putExtra(Intent.EXTRA_CC, ccs);
		intent.putExtra(Intent.EXTRA_TEXT, "body");
		intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
		
		ArrayList imageUris = new ArrayList();
		imageUris.add(Uri.parse("file:///sdcard/Chrysanthemum.jpg"));
		imageUris.add(Uri.parse("file:///sdcard/Desert.jpg"));		
		intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
		intent.setType("image/*");
		intent.setType("message/rfc882");
		Intent.createChooser(intent, "Choose Email Client");
		startActivity(intent);
当邮件需要带附件时,类型要这样设置:intent.setType("application/octet-stream");此时,对于附件文件的转换如下
imageUris = new ArrayList<Uri>();
Uri.fromFile(new File(文件的绝对路径1)
Uri.fromFile(new File(文件的绝对路径2)
Uri.fromFile(new File(文件的绝对路径3)
putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris)

第二种方法,通过Java Mail的方式发送邮件,通过发送日志信息为例来解决

思路,首先判断网络是否可用,如果可用的话就发送邮件到指定的邮箱。

/**
	 * 判断网络是否可用
	 * 
	 * @param activity
	 * @return
	 */
	public boolean isNetworkAvailable(Activity activity) {
		Context context = activity.getApplicationContext();
		// 获取手机所有连接管理对象(包括对WIFI,net等连接的管理)
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connectivityManager == null) {
			return false;
		} else {
			// 获取NetworkInfo对象
			NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

			Log.e("TAG", networkInfo.length + "");
			if (networkInfo != null && networkInfo.length > 0) {
				for (int i = 0; i < networkInfo.length; i++) {
					System.out.println(i + "===状态==="
							+ networkInfo[i].getState());
					System.out.println(i + "===类型==="
							+ networkInfo[i].getTypeName());
					// 判断当前网络状态是否为连接状态
					if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {// 如果网络连接,再判断是WIFI连接还是移动数据
						if (networkInfo[i].getTypeName().equals("WIFI")) {// 若是WIFI,则判断WiFI是否为可用外网
							return checkWifiState();
						} else {// 若是移动数据连接,则判断是否是4G网络

							return true;
						}
					}
				}
			}
		}
		ToastUtils.showToast(this, "当前没有可用网络!", Toast.LENGTH_SHORT);
		return false;
	}

第二步,检查wifi是否为可用wifi

/**
	 * 检查WIFI是否为可用外网
	 */
	public boolean checkWifiState() {
		WifiConnectTool wifiTool = new WifiConnectTool(this);
		String[] data = wifiTool.getWifiStateAndIP();

		if ("192.254.0.250".equals(data[1])) {
			ToastUtils.showToast(this, "外网连接失败,请重新选择可用外网WIFI!", Toast.LENGTH_LONG);
			return false;
		}
		return true;
	}

第三步,如果网络可用,就可以发送文件到邮箱了

if (isNetworkAvailable(this)) {
	// 此处是发送文件到邮箱的逻辑
	// 发送文件的对话框
	showDialogSendCSV();
} else {
	return;
}


private void showDialogSendCSV() {

		AlertDialog.Builder adb = new AlertDialog.Builder(this);
		dialog = adb.create();

		View view = getLayoutInflater().inflate(R.layout.setemail_dialog, null);
		
		ImageView iv_arrow = (ImageView) view.findViewById(R.id.iv_arrow);
		ImageView iv_add = (ImageView) view.findViewById(R.id.add_contact);
		
		final EditText email_contact = (EditText) view
				.findViewById(R.id.email_contact);
		/*final EditText email_title = (EditText) view
				.findViewById(R.id.email_title);
		final EditText email_content = (EditText) view
				.findViewById(R.id.email_content);*/

		//下拉框,显示出保存的收件人
		iv_arrow.setOnClickListener(new OnClickListener() {
			
			private PopupWindow pop;

			@Override
			public void onClick(View v) {

				if(popWindow == null){
					pop = new PopupWindow(DataManagerActivity.this);
					int with = DensityUtil.dip2px(DataManagerActivity.this, 50);
					pop.setWidth(email_contact.getWidth()+with); // 让 弹出窗体与输入框宽度一样
					int hight = DensityUtil.dip2px(DataManagerActivity.this, 130);
					pop.setHeight(hight);
					
					pop.setContentView(listView1);
					
					pop.setFocusable(true); // 默认 popWindow 不获得焦点,这样,listview 条目的无法点击
					
				}
				listView1.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						
						// 将对应的文字写入输入框
						email_contact.setText(msgList.get(position));
						email_contact.setSelection(msgList.get(position).length());
						
						// 关闭弹出窗体
						pop.dismiss();
					}
				});
				
				// 切换popWidnows的显示
				if(pop.isShowing()){
					pop.dismiss();
				}else{
					pop.showAsDropDown(email_contact, 0, 0); // 弹出窗体显示在 输入框的下方
				}
			}
		});
		//添加收件人到下拉框
		iv_add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String msg = email_contact.getText().toString().trim();
				if(!TextUtils.isEmpty(msg)){
					if(!dataProvider.isExist(msg)){
						//添加到集合
						dataProvider.addContact(msg);
						msgList.add(msg);
						adapter2.notifyDataSetChanged();
					}
				}
			}
		});
		
		Button btnOk = (Button) view.findViewById(R.id.btn_ok);
		Button btnCancel = (Button) view.findViewById(R.id.btn_cancel);

		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String contact = email_contact.getText().toString().trim();
				/*String title = email_title.getText().toString().trim();
				String content = email_content.getText().toString().trim();*/
				// 检查邮箱格式是否正确
				if (contact
						.matches("\\b^['_a-z0-9-\\+]"
								+ "+(\\.['_a-z0-9-\\+]+)*@[a-z0-9-]+"
								+ "(\\.[a-z0-9-]+)*\\.([a-z]{2}|aero|arpa|asia"
								+ "|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|"
								+ "name|nato|net|org|pro|tel|travel|xxx)$\\b")) {
				} else {
					ToastUtils.showToast(DataManagerActivity.this, "邮箱格式不正确", Toast.LENGTH_SHORT);
					return;
				}
				/*if (TextUtils.isEmpty(title)) {
					ToastUtils.showToast(DataManagerActivity.this, "标题不能为空", Toast.LENGTH_SHORT);
					return;
				}
				emailTitle = title;
				emailContent = content;*/
				emailReciver = new String[] { contact };
				// 发送文件到邮箱(调用系统的软件)
				//sendCSVFileIntent();
				// 发送文件到邮箱(使用JavaMail)
				new Thread(){
					public void run() {
						
						sendCSVFilByJavaMail();
					};
				}.start();
				dialog.dismiss();
			}
		});
		btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();

			}
		});
		dialog.setCancelable(false);
		dialog.setView(view, 0, 0, 0, 0); // 设置 view

		dialog.show();
	}

	//通过JavaMail发送文件
	private void sendCSVFilByJavaMail() {
		sb.setLength(0);
		//先设置邮件
		MailSendInfo info = new MailSendInfo();
    	info.setMailServerHost("smtp.163.com");
    	info.setMailServerPost("25");
    	info.setValidate(true);
    	info.setUserName("11122222@163.com");
    	info.setPassWord("333333");//邮箱密码
    	info.setFromAddress("@163.com");
    	//以下三个内容是需要修改的
    	info.setToAddress(emailReciver[0]);
    	if(selectSendItem.size()>1){
    		
    		info.setSubject(selectSendItem.get(0)+"...");
    	}else{
    		info.setSubject(selectSendItem.get(0));
    	}
    	sb.append("收到的文件:");
    	for (int i = 0; i < selectSendItem.size(); i++) {
    		sb.append(selectSendItem.get(i));
    		if(i < (selectSendItem.size()-1)){
    			sb.append(", ");
    		}
		}
    	Log.e("邮件内容:", sb.toString());
    	info.setContent(sb.toString());
    	
    	MultiMailSend senMail = new MultiMailSend(path);//这个类用来发送邮件
    	
    	senMail.sendAttachment(info,selectSendItem);
		
	}
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
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;

import com.zrd.111.model.MailSendInfo;

import android.os.Environment;
import android.util.Log;

/**
 * 以下是利用JavaMail的API来创建和发送邮件
 * 多附件发送邮件类,并且发送邮件给多个接受者、抄送文件
 * @author Administrator
 *
 */
public class MultiMailSend {

	private MailSendInfo info;
	private String path;
	public MultiMailSend(String path){
		this.path = path;
	}
	/**
	 * 以文本格式发送邮件
	 * @param info 待发送的邮件信息
	 * @return
	 */
	public void sendTextMail(MailSendInfo info){
		this.info = info;
		//判断是否需要身份验证
		Properties properties = info.getProperties();
		//1、根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession  = Session.getDefaultInstance(properties);
		//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
		sendMailSession.setDebug(true);
		try {
			
			//2、通过session得到transport对象,以便连接邮箱并发送  
            Transport transport = sendMailSession.getTransport();  
            //3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给SMTP服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
			transport.connect("smtp.163.com", ".com", "11"); 
			//4、创建邮件消息
			Message mailMessage = createSimpleMail(sendMailSession);
			//5、发送邮件消息
			transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
			transport.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 发送内容带有图片的邮件
	 */
	public void sendImageEmail(MailSendInfo info){
		this.info = info;
		Properties properties = info.getProperties();
		//1、根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession  = Session.getDefaultInstance(properties);
		//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
		sendMailSession.setDebug(true);
		try {
			
			//2、通过session得到transport对象,以便连接邮箱并发送  
            Transport transport = sendMailSession.getTransport();  
            //3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给SMTP服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
			transport.connect("smtp.163.com", "1112222222.com", "3333333"); 
			//4、创建邮件消息
			Message mailMessage = createImageMail(sendMailSession);
			//5、发送邮件消息
			transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
			transport.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 发送带有附件的邮件
	 * @param info
	 */
	public void sendAttachment(MailSendInfo info,ArrayList<String> list){
		this.info = info;
		Properties properties = info.getProperties();
		//1、根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession  = Session.getDefaultInstance(properties);
		//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
		sendMailSession.setDebug(true);
		try {
			//2、通过session得到transport对象,以便连接邮箱并发送  
            Transport transport = sendMailSession.getTransport();  
            //3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给SMTP服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
			transport.connect("smtp.163.com", "@163.com", "811"); 
			//4、创建邮件消息
			Message mailMessage = createAttachmentMail(sendMailSession,list);
			//5、发送邮件消息
			transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
			transport.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送复杂邮件
	 * @param info
	 */
	public void sendMixedMail(MailSendInfo info,ArrayList<String> list){

		this.info = info;
		Properties properties = info.getProperties();
		//1、根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession  = Session.getDefaultInstance(properties);
		//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
		sendMailSession.setDebug(true);
		try {
			//2、通过session得到transport对象,以便连接邮箱并发送  
            Transport transport = sendMailSession.getTransport();  
            //3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给SMTP服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
			transport.connect("smtp.163.com", "11122222222@163.com", "333333"); 
			//4、创建邮件消息
			Message mailMessage = createMixedMail(sendMailSession,list);
			//5、发送邮件消息
			transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
			transport.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 创建复杂的邮件(包括图片和多附件的邮件)
	 * @param sendMailSession
	 * @param list 是选中CSV文件的集合
	 * @return
	 */
	private Message createMixedMail(Session sendMailSession,ArrayList<String> list) {
		// 创建邮件
		MimeMessage message = null;
		try {
			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());

			// 正文
			MimeBodyPart text = new MimeBodyPart();
			text.setContent(info.getContent(),
					"text/html;charset=UTF-8");

			/*// 图片
			MimeBodyPart image = new MimeBodyPart();
			image.setDataHandler(new DataHandler(new FileDataSource(Environment.getExternalStorageDirectory().getPath()+"/猫咪.jpg")));
			image.setContentID("猫咪.jpg");*/

			// 附件1
			MimeBodyPart attach = new MimeBodyPart();
			DataHandler dh = new DataHandler(new FileDataSource(Environment.getExternalStorageDirectory().getPath()+"/zed_authorize.txt"));
			attach.setDataHandler(dh);
			attach.setFileName(dh.getName());

			// 附件2
			MimeBodyPart attach2 = new MimeBodyPart();
			DataHandler dh2 = new DataHandler(new FileDataSource(Environment.getExternalStorageDirectory().getPath()+"/error_log_z9.txt"));
			attach2.setDataHandler(dh2);
			attach2.setFileName(MimeUtility.encodeText(dh2.getName()));

			/*// 描述关系:正文和图片
			MimeMultipart mp1 = new MimeMultipart();
			mp1.addBodyPart(image);
			mp1.setSubType("related");*/

			// 描述关系:正文和附件
			MimeMultipart mp2 = new MimeMultipart();
			mp2.addBodyPart(text);
			mp2.addBodyPart(attach);
			mp2.addBodyPart(attach2);

			/*// 代表正文的BodyPart
			MimeBodyPart content = new MimeBodyPart();
			content.setContent(mp1);
			mp2.addBodyPart(content);*/

			mp2.setSubType("mixed");
			message.setContent(mp2);
			message.saveChanges();

			// 将创建的Email写入到E盘存储
			//message.writeTo(new FileOutputStream("E:\\MixedMail.eml"));
		} catch (Exception e) {
			Log.e("TAG", "创建复杂邮件失败");
			e.printStackTrace();
		}
		// 返回创建好的的邮件
		return message;

	}
	/**
	 * 创建带有附件的邮件
	 * @param sendMailSession
	 * @param list 选中的CSV文件的集合
	 * @return
	 */
	private Message createAttachmentMail(Session sendMailSession,ArrayList<String> list) {
		//创建邮件
		MimeMessage message = null;
		try {
			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);
			for (int i = 0; i < list.size(); i++) {
				// 创建邮件附件
				MimeBodyPart attach = new MimeBodyPart();
				DataHandler dh = new DataHandler(new FileDataSource(path + list.get(i)));
				attach.setDataHandler(dh);
				attach.setFileName(MimeUtility.encodeText(dh.getName())); 
				mp.addBodyPart(attach);
			}
			mp.setSubType("mixed");
			message.setContent(mp);
			message.saveChanges();
			// 将创建的Email写入到E盘存储
			//message.writeTo(new FileOutputStream("E:\\attachMail.eml"));
		} catch (Exception e) {
			Log.e("TAG", "创建带附件的邮件失败");
			e.printStackTrace();
		}
		// 返回生成的邮件
		return message;
	}
	/**
	 *生成一封邮件正文带图片的邮件
	 * @param sendMailSession
	 * @return
	 */
	private MimeMessage createImageMail(Session sendMailSession) {
		//创建邮件
		MimeMessage mailMessage = null;
		try {
			mailMessage = new MimeMessage(sendMailSession);
			// 设置邮件的基本信息
			//创建邮件发送者地址
			Address from = new InternetAddress(info.getFromAddress());
			//设置邮件消息的发送者
			mailMessage.setFrom(from);
			//创建邮件的接受者地址,并设置到邮件消息中
			Address to = new InternetAddress(info.getToAddress());
			 //设置邮件消息的接受者, Message.RecipientType.TO属性表示接收者的类型为TO 
			mailMessage.setRecipient(Message.RecipientType.TO, to);
			//邮件标题
			mailMessage.setSubject(info.getSubject());
			// 准备邮件数据
			// 准备邮件正文数据
			MimeBodyPart text = new MimeBodyPart();
			text.setContent("这是一封邮件正文带图片<img src='cid:xxx.jpg'>的邮件", "text/html;charset=UTF-8");
			// 准备图片数据
			MimeBodyPart image = new MimeBodyPart();
			DataHandler dh = new DataHandler(new FileDataSource("src\\1.jpg"));
			image.setDataHandler(dh);
			image.setContentID("xxx.jpg");
			// 描述数据关系
			MimeMultipart mm = new MimeMultipart();
			mm.addBodyPart(text);
			mm.addBodyPart(image);
			mm.setSubType("related");
			mailMessage.setContent(mm);
			mailMessage.saveChanges();
			//将创建好的邮件写入到E盘以文件的形式进行保存
			mailMessage.writeTo(new FileOutputStream("E:\\ImageMail.eml"));
			//返回创建好的邮件
		} catch (Exception e) {
			Log.e("TAG", "创建带有图片的邮件消息失败");
			e.printStackTrace();
		}
		return mailMessage;
	}
	/**
	 * 创建纯文本内容的邮件消息
	 * @param sendMailSession
	 * @return
	 */
	public MimeMessage createSimpleMail(Session sendMailSession){
		MimeMessage mailMessage = null;
		try {
			//根据session创建一条邮件信息
			mailMessage = new MimeMessage(sendMailSession);
			//创建邮件发送者地址
			Address from = new InternetAddress(info.getFromAddress());
			//设置邮件消息的发送者
			mailMessage.setFrom(from);
			//创建邮件的接受者地址,并设置到邮件消息中
			Address to = new InternetAddress(info.getToAddress());
			 //设置邮件消息的接受者, Message.RecipientType.TO属性表示接收者的类型为TO 
			mailMessage.setRecipient(Message.RecipientType.TO, to);
			//设置邮件标题
			mailMessage.setSubject(info.getSubject());
			//设置邮件内容
			mailMessage.setText(info.getContent());
			//设置邮件发送的时间
			mailMessage.setSentDate(new Date());
		} catch (Exception e) {
			Log.e("TAG", "邮件消息创建失败");
			e.printStackTrace();
		}
		return mailMessage;
	}
}

下面是发送邮件的字段信息

import java.util.Properties;

/**
 * 邮件的设置信息
 * @author Administrator
 *
 */
public class MailSendInfo {

	/**
	 * 发送邮件的服务器的IP和端口
	 */
	private String mailServerHost;
	private String mailServerPort;
	/**
	 * 邮件发送者的地址
	 */
	private String fromAddress;
	/**
	 * 邮件接受者的地址
	 */
	private String toAddress;
	/**
	 * 登陆邮件发送服务器的用户名和密码
	 */
	private String userName;
	private String passWord;
	/**
	 * 是否需要身份验证
	 */
	private boolean validate = false;
	/**
	 * 邮件发送的主题
	 */
	private String subject;
	/**
	 * 邮件发送的内容
	 */
	private String content;
	/**
	 * 邮件附件的文件名
	 */
	private String[] attachFileNames;  
	
	/**
	 * 获取邮件会话属性
	 * @return
	 */
	public Properties getProperties(){
		Properties p = new Properties();
		p.put("mail.smtp.host", this.mailServerHost);
		p.put("mail.smtp.port", this.mailServerPort);
		p.put("mail.transport.protocol", "smtp");
		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 getMailServerPost() {
		return mailServerPort;
	}

	public void setMailServerPost(String mailServerPost) {
		this.mailServerPort = mailServerPost;
	}

	public String getFromAddress() {
		return fromAddress;
	}

	public void setFromAddress(String fromAddress) {
		this.fromAddress = fromAddress;
	}

	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 getPassWord() {
		return passWord;
	}

	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}

	public boolean isValidate() {
		return validate;
	}

	public void setValidate(boolean validate) {
		this.validate = validate;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String[] getAttachFileNames() {
		return attachFileNames;
	}

	public void setAttachFileNames(String[] attachFileNames) {
		this.attachFileNames = attachFileNames;
	}
	
}

显示发送邮件对话框是自定义的对话框,XML代码如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:gravity="center" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal" >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="设置邮件信息"
                android:textSize="18sp" />
        </LinearLayout>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginTop="15dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="3.0"
            android:gravity="right"
            android:text="邮箱名称:" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1.0" >

            <EditText
                android:id="@+id/email_contact"
                android:layout_width="180dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="50dp"
                android:textSize="12sp"
                 />

            <ImageView
                android:id="@+id/iv_arrow"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_alignRight="@id/email_contact"
                android:layout_alignTop="@id/email_contact"
                android:background="@drawable/down_arrow" />

            <ImageView
                android:id="@+id/add_contact"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginLeft="5dp"
                android:layout_toRightOf="@id/iv_arrow"
                android:background="@drawable/btn_add_contact"
                android:contentDescription="@string/app_name" />
        </RelativeLayout>
    </LinearLayout>

    <!-- <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="3.0"
            android:gravity="right"
            android:text="邮件标题:" />

        <EditText
            android:id="@+id/email_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="50dp"
            android:layout_weight="1.0" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="3.0"
            android:gravity="right"
            android:text="邮件内容:" />

        <EditText
            android:id="@+id/email_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="50dp"
            android:layout_weight="1.0" />
    </LinearLayout> -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_ok"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="确定发送" />

        <Button
            android:id="@+id/btn_cancel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="取消发送" />
    </LinearLayout>

</LinearLayout>

注意,

1、在MultiMailSend类中发送普通文本和附件,我在android上调试过可以使用,但发送图片,我没调试通过,需要在web中才能发送成功,代码先贴在这里,

等以后找到了解决方法后再分享

2、需要加上联网权限

3、要读取SD卡中的文件,要加上读取SD卡的权限

    原文作者:zhizuyiwang
    原文地址: https://blog.csdn.net/zhizuyiwang/article/details/51568210
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞