今天做東西的時候突然遇到需要發郵件的問題,然後就使用SMTP協議進行郵件的發送。用了一個工具類簡化郵件發送的功能,
在這次試驗中,我使用了自己的QQ郵箱進行發送郵件的發送者。
public class MailUtils {
public static void sendMail(String email, String emailMsg)
throws AddressException, MessagingException {
// 1.創建一個程序與郵件服務器會話對象 Session
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");
props.setProperty("mail.host", "smtp.qq.com");
props.setProperty("mail.smtp.auth", "true");// 指定驗證爲true
// 創建驗證器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("QQ號碼", "授權碼");
}
};
Session session = Session.getInstance(props, auth);
// 2.創建一個Message,它相當於是郵件內容
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("QQ郵箱全部名稱")); // 設置發送者
message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 設置發送方式與接收者
message.setSubject("用戶激活");
// message.setText("這是一封激活郵件,請<a href='#'>點擊</a>");
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.創建 Transport用於將郵件發送
Transport.send(message);
}
}
文章中牽涉到一個授權碼的問題,發送郵件所使用的郵箱中需要設置將SMTP開啓並獲取授權碼,在這裏以QQ郵箱爲例:
什麼是授權碼,它又是如何設置?
這個時候如果使用163或者126郵箱的話,應該就可以實現發郵件的功能了,但是QQ郵箱的話這時會報一個這樣的錯誤:
提示說你的這個資源需要提供像ssl那樣的加密方式,具體的請參考騰訊後面的那個網址。
這個時候就需要在代碼中提供ssl的加密方式了,
添加後的代碼爲
// 1.創建一個程序與郵件服務器會話對象 Session
//開啓ssl加密
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
sf.setTrustAllHosts(true);
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
props.setProperty("mail.host", "smtp.qq.com");
props.setProperty("mail.smtp.auth", "true");// 指定驗證爲true
這樣就可以在需要發送郵件的位置直接調用這個sendmail方法就可以實現發送郵件的功能了。
個人見解,僅供參考...