Android 发送邮件mail

andoid利用javamail发送邮件,这里以163邮箱发送为例,126邮箱服务器地址为:smtp.126.com

<span style="font-size:18px;">package com.example.sendemail;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import android.os.Bundle;
import android.util.Log;
import android.app.Activity;

public class MainActivity extends Activity {

	Properties props;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		new Thread() {

			@Override
			public void run() {
				super.run();

				// 实例化属性对象Properties
				props = new Properties();
				// 设置smtp的服务器地址
				props.put("mail.smtp.host", "smtp.163.com");
				// 设置服务器需要身份验证
				props.put("mail.smtp.auth", "true");
				// 创建会话session来管理连接
				Session session = Session.getDefaultInstance(props,
				// 匿名内部类创建authenticator实例
						new javax.mail.Authenticator() {
							@Override
							protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
								String username = "[email protected]";// 邮箱登陆账号
								String pwd = "qqqq";
								return new PasswordAuthentication(username, pwd);
							}
						});

				// 实例化MimeMessage对象
				MimeMessage message = new MimeMessage(session);
				try {
					// 设置发送方邮件地址 "FROM"为昵称
					Address addressFrom = new InternetAddress(
							"[email protected]", "FROM");
					// 设置接收方方邮件地址
					Address addressTo1 = new InternetAddress(
							"[email protected]", "To");
					// 设置接收方方邮件地址
					Address addressTo2 = new InternetAddress(
							"[email protected]", "To");
					// 收件人地址 抄送
					Address addressCopy = new InternetAddress(
							"[email protected]", "abc");
					// 创建邮件内容
					message.setContent("hello", "text/plain");// 或者message.setText("hello");
					// 设置标题
					message.setSubject("title");
					// 设置发件人
					message.setFrom(addressFrom);
					// 添加收件人 在这里可以群发
					message.addRecipients(Message.RecipientType.TO,
							new Address[] { addressTo1, addressTo2 });
					// 抄送人
					message.addRecipient(Message.RecipientType.CC, addressCopy);
					message.saveChanges();
					// 发送邮件
					Transport transport = session.getTransport("smtp");// 创建连接
					transport.connect("smtp.163.com", "[email protected]",
							"qqqq");
					Transport.send(message);
					Log.i("mail", "发送成功");
					transport.close();
				} catch (UnsupportedEncodingException e) {
					Log.i("mail", "发送失败    UnsupportedEncodingException");
					e.printStackTrace();
				} catch (MessagingException e) {
					Log.i("mail", "发送失败,密码错误");
					e.printStackTrace();
				}
			}
		}.start();
	}
}
</span>
依赖的包下载:

http://download.csdn.net/detail/u014071669/7920533

你可能感兴趣的:(邮件,mail,javamail)