生活随笔
收集整理的這篇文章主要介紹了
Java 发送163邮件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【背景】
??SSH網上商城中使用的郵件發送是局域網內的,Java這么強大,干嘛要弄局域網的呢,要發就發真實的郵件。
【前提】
??開啟自己賬號的163郵箱協議和授權碼,授權碼和登錄郵箱賬號的密碼不是同一個,郵箱賬號密碼是登錄郵箱的密碼,授權碼是第三方登錄授權的密碼,比如Foxmail或其它程序,像編寫的Java程序也是第三方。
我這里已經開啟了,但是我忘了,然后我是重置的,這個步驟很簡單,就不寫了。記住這個授權碼,在Java里編寫的時候要用到。
【代碼編寫】
需要導入1個包,mail.jar。下載鏈接:https://pan.baidu.com/s/124oEBsE4Qrw9e8TXaHoFQA 提取碼:3mbm
然后在該jar包上,右擊 Build Path → Add to Build Path,就可以使用了。
import java
.util
.Properties
;import javax
.mail
.Authenticator
;
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
;public class Main {public static String
sendMail(String to
, String title
, String content
) {Properties props
= new Properties();props
.setProperty("mail.host", "smtp.163.com"); props
.setProperty("mail.transport.protocol", "SMTP"); props
.setProperty("mail.smtp.auth", "true"); Authenticator authenticator
= new Authenticator() {public PasswordAuthentication
getPasswordAuthentication() {return new PasswordAuthentication("*******5602", "授權碼"); }};Session session
= Session
.getInstance(props
, authenticator
);MimeMessage mess
= new MimeMessage(session
);try {mess
.setFrom(new InternetAddress("*******5602@163.com")); mess
.setRecipients(Message
.RecipientType
.TO
, to
); mess
.setSubject(title
); mess
.setContent(content
, "text/html;charset=utf-8"); Transport
.send(mess
);} catch (MessagingException e
) {e
.printStackTrace();return "發送郵件失敗, 原因:" + e
.getMessage();}return "發送郵件成功!接收人:" + to
;}public static void main(String
[] args
) {String mess
= sendMail("*******5602@163.com", "測試郵件", "<h1>這是一封測試郵件,來自Java客戶端程序</h1>");System
.out
.println(mess
); }}
運行:
【相關資料學習】
Java中Properties類的操作
Java Mail 發送郵件之——簡單實現
如果有異常出現,參考博客535 authentication failed的問題
總結
以上是生活随笔為你收集整理的Java 发送163邮件的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。