

為什么嘗試運行了幾次工具類,都沒有接收到郵件??
uj5u.com熱心網友回復:
是否需要調整一些引數?idea maven模式下 pom.xml應該是配置了jar包路徑了uj5u.com熱心網友回復:
package cn.itcast.travel.util;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 = ""; // 發件人稱號,同郵箱地址
private static final String PASSWORD = ""; // 如果是qq郵箱可以使戶端授權碼,或者登錄密碼
/**
*
* @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 { // 做測驗用
MailUtils.sendMail("[email protected]","你好,這是一封測驗郵件,無需回復。","測驗郵件");
System.out.println("123");
}
原始碼
uj5u.com熱心網友回復:
應該是 Transport.send(message); 這個弄錯了try {
Session session = Session.getInstance(prop);
// 開啟Session的debug模式,這樣就可以查看到程式發送Email的運行狀態
session.setDebug(true);
// 2、通過session得到transport物件
Transport ts = session.getTransport();
// 3、使用郵箱的用戶名和密碼連上郵件服務器,發送郵件時,發件人需要提交郵箱的用戶名和密碼給smtp服務器,
// 用戶名和密碼都通過驗證之后才能夠正常發送郵件給收件人。
ts.connect(base_host, base_from, base_password);
// 4、創建郵件
// 創建郵件物件
MimeMessage message = new MimeMessage(session);
// 指明郵件的發件人
message.setFrom(new InternetAddress(base_from));
// 指明郵件的收件人,現在發件人和收件人是一樣的,那就是自己給自己發
message.setRecipients(Message.RecipientType.TO, new InternetAddress().parse(to));// 收件人
// 郵件的標題
message.setSubject(title);
// 郵件的文本內容
message.setContent(text, "text/html;charset=UTF-8");
// 5、發送郵件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
} catch (Exception e) {
logger.error("郵件發送失敗 ----{}", e.getMessage());
}
uj5u.com熱心網友回復:
上面很明顯有錯誤資訊把?uj5u.com熱心網友回復:
郵件的客戶端需要開通一個協議 才能從本地發送 已解決轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/50874.html
標籤:Web 開發
