Android 发送邮件

作者: 丶麦芽 | 来源:发表于2017-04-01 16:52 被阅读300次

依赖

compile 'com.sun.mail:android-mail:1.5.5'
compile 'com.sun.mail:android-activation:1.5.5'

使用

//创建配置文件
Properties props = new Properties();
//开启认证
props.put("mail.smtp.auth", true);
//设置协议方式
props.put("mail.transport.protocol", "smtp");
//设置主机名
props.put("mail.smtp.host", String host);
//设置SSL加密(未采用SSL时,端口一般为25,可以不用设置;采用SSL时,端口为465,需要显示设置)
props.setProperty("mail.smtp.port", String port);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", String port);
//设置账户和密码
props.put("mail.smtp.username",String username);
props.put("mail.smtp.password",String password);
//创建会话,getDefaultInstace得到的始终是该方法初次创建的缺省的对象,getInstace每次获取新对象
Session session = Session.getInstance(props,new SmtpAuthenticator());
//显示错误信息
session.setDebug(true);
//创建发送时的消息对象
MimeMessage message = new MimeMessage(session);
//设置发送发的账户和名称
message.setFrom(new InternetAddress(String senderAccount,String senderName,"UTF-8"));
//获取收件方的账户和名称
message.setRecipients(MimeMessage.RecipientType.TO,String receiverAccount);
//设置主题
message.setSubject(emailMessage.getSubject());
//设置内容
message.setContent(String content,"text/html;charset=UTF-8");
//发送
Transport.send(message);

登录认证类

private static class SmtpAuthenticator extends Authenticator {    
private String mUsername ;    
private String mPassword ;    
public SmtpAuthenticator(String username,String password) {        
    super();        
    this.mUsername = username;        
    this.mPassword = password;    
}    
@Override    
public PasswordAuthentication getPasswordAuthentication() {        
    if ((mUsername != null) && (mUsername.length() > 0) && (mPassword != null)&& (mPassword.length() > 0)) {           
        return new PasswordAuthentication(mUsername, mPassword);      
  }      
 return null;    
}

相关文章

网友评论

    本文标题:Android 发送邮件

    本文链接:https://www.haomeiwen.com/subject/tcoiottx.html