Android · 2015年2月11日 0

Android Email编程

Android Email编程
1.android自带邮件系统
//创建Intent
Intent intent=new Intent();
//设置对象动作
intent.setAction(Intent.ACTION_SEND);
//设置对方邮件地址
intent.putExtra(Intent.ExTRA_EMAIL,new String[]{‘abc@163.com’,’a@gmail.com’});
//设置标题内容
intent.putExtra(Intent.EXTRA_SUBJECT,”test”);
//设置邮件文本内容
intent.putExtra(Intent.EXTRA_TEXT,”text_mail”);
//启动一个新的Activity,‘sending mail…’是在启动这个activity的等待时间时所显示的文字
startActivity(Intent.creatChooser(intent,”sending mail…”));

2.android JavaMail设计

android中使用javamail需要依赖3个包:activation.jar,additionnal.jar,mail.jar
对于实现邮件的发送,还需要确保发送方能连接到发送方邮件服务器,一般邮件服务器都需要认证,只有通过认证才能连接,从而将邮件发出去。
以126为例:
//创建一个身份验证,即定义Authenticator的子类,并重载getPasswordAuthentication()方法
class PuoupAuthenticatior extends Authenticator{
public PasswordAuthenication getPasswordAuthentication(){
String username=”from”;//邮箱登陆账号
String pwd=””;//登录密码
//返回PasswrodAuthentication对象
return new PasswordAuthentication(username,pwd);
}
}
//实例化实现对象Properties
Properties props=new Properties();
//设置smtp的服务器地址是:smtp.126.com
props.put(“mail.smtp.host”,”smtp.126.com”);
props.put(“mail.smtp.auth”,”true”);//设置smtp服务器身份验证
PopupAuthenticator auth=new PopupAuthenticator();//创建身份验证的实例
//创建会话(Session),用它管理连接
Session session=Session.getInstance(props,auth);
//实例化MimeMessage对象
MimeMessage message=new MimeMessage(session);
//设置发送方邮件地址
Address addressFrom=new InternetAddress(“a@126.com”,”FROM”);
//设置收件人邮件地址
Address addressTo=new InternetAddress(“b@126.com”,”TO”);
//收件人地址
Address addressCopy=new InternetAddress(“abc@gmail.com”,”abc”);
//创建邮件内容
message.setContent(“hello”,”text/plain”);
//或者使用message.setText(“Hello”);
message.setSubject(“Title”);
message.setFrom(addressFrom);
message.setRecipient(Message.RecipientType.TO,addressTO);
message.setRecipient(Message.RecipientType.CC,addressCopy);
message.saveChanges();
//发送邮件
Transport transport=session.getTransport(“smtp”);//创建连接
transport.connect(“smtp.126.com”,”from”,”123456″);
transport.send(message);//发送信息
transport.close();关闭连接

Share this: