Android 發(fā)送郵件

依賴

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

使用

//創(chuàng)建配置文件
Properties props = new Properties();
//開啟認(rèn)證
props.put("mail.smtp.auth", true);
//設(shè)置協(xié)議方式
props.put("mail.transport.protocol", "smtp");
//設(shè)置主機(jī)名
props.put("mail.smtp.host", String host);
//設(shè)置SSL加密(未采用SSL時(shí),端口一般為25,可以不用設(shè)置;采用SSL時(shí),端口為465,需要顯示設(shè)置)
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);
//設(shè)置賬戶和密碼
props.put("mail.smtp.username",String username);
props.put("mail.smtp.password",String password);
//創(chuàng)建會(huì)話,getDefaultInstace得到的始終是該方法初次創(chuàng)建的缺省的對象,getInstace每次獲取新對象
Session session = Session.getInstance(props,new SmtpAuthenticator());
//顯示錯(cuò)誤信息
session.setDebug(true);
//創(chuàng)建發(fā)送時(shí)的消息對象
MimeMessage message = new MimeMessage(session);
//設(shè)置發(fā)送發(fā)的賬戶和名稱
message.setFrom(new InternetAddress(String senderAccount,String senderName,"UTF-8"));
//獲取收件方的賬戶和名稱
message.setRecipients(MimeMessage.RecipientType.TO,String receiverAccount);
//設(shè)置主題
message.setSubject(emailMessage.getSubject());
//設(shè)置內(nèi)容
message.setContent(String content,"text/html;charset=UTF-8");
//發(fā)送
Transport.send(message);

登錄認(rèn)證類

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;    
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容