說明
- 使用自己的郵箱向第三方用戶發送激活碼等重要郵件。
- 你必須先將自己郵箱的POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務打開,並獲得一個授權碼。
代碼
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* 發郵件工具類
*/
public final class MailUtils {
private static final String USER = "[email protected]"; // 發件人稱號,同郵箱地址
private static final String PASSWORD = "rkwaniackaocjib"; /使用客戶端授權碼
/**
*
* @param to 收件人郵箱
* @param text 郵件正文
* @param title 標題
*/
/* 發送驗證信息的郵件 */
public static boolean sendMail(String to, String text, String title){
try {
final Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");
// 發件人的賬號
props.put("mail.user", USER);
//發件人的密碼
props.put("mail.password", PASSWORD);
// 構建授權信息,用於進行SMTP進行身份驗證
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用戶名、密碼
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用環境屬性和授權信息,創建郵件會話
Session mailSession = Session.getInstance(props, authenticator);
// 創建郵件消息
MimeMessage message = new MimeMessage(mailSession);
// 設置發件人
String username = props.getProperty("mail.user");
InternetAddress form = new InternetAddress(username);
message.setFrom(form);
// 設置收件人
InternetAddress toAddress = new InternetAddress(to);
message.setRecipient(Message.RecipientType.TO, toAddress);
// 設置郵件標題
message.setSubject(title);
// 設置郵件的內容體
message.setContent(text, "text/html;charset=UTF-8");
// 發送郵件
Transport.send(message);
return true;
}catch (Exception e){
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws Exception { // 做測試用
boolean flag=MailUtils.sendMail("[email protected]","郵件測試成功","小郵件");
if(flag) System.out.println("郵件發送成功!");
else System.out.println("郵件發送失敗!");
}
}
ATFWUS --Writing By 2020–04-11