網易雲郵箱接收驗證信息
需要到一個郵箱的jar包,如下
public final class MailUtils {
// 這裏填寫發件人郵箱地址(即設置了授權碼的郵箱地址)
private static final String USER = "[email protected]";
private static final String PASSWORD = "xxxxxx"; // 你設置的授權碼
/**
*
* @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.163.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 { // 測試用
// 這裏填寫接受郵件的郵箱地址
MailUtils.sendMail("[email protected]","你好,這是一封測試郵件,無需回覆。","測試郵件");
System.out.println("發送成功");
}
}