1,設定163郵箱
開啟POP3/SMTP/IMAP
2,依賴
<dependency>
<groupId>jakarta.mail</groupId>
<artifactId>jakarta.mail-api</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>2.0.1</version>
</dependency>
3,MailUtil
package com.xxx.util;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class MailUtil {
/**
* 發件人郵箱
*/
private static final String SENDER_ACCOUNT = "xxxxx@163.com";
/**
* 郵箱密碼/授權碼
*/
private static final String AUTH_CODE = "xxxxxxxx";
/**
* 傳送郵件
*
* @param direction 收件人郵箱地址
* @param subject 郵件名稱/標題
* @param message 訊息、內容
*/
public static boolean sendMail(String direction, String subject, String message) {
Properties props = new Properties();
// 開啟debug除錯
props.setProperty("mail.debug", "true");
// 傳送伺服器需要身份驗證
props.setProperty("mail.smtp.auth", "true");
// 設定郵件伺服器主機名
props.setProperty("mail.host", "smtp.163.com");
// 使用SSL,埠號994
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
try {
// 建立有指定屬性的session
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(SENDER_ACCOUNT, AUTH_CODE);
}
});
// 新建訊息
Message msg = new MimeMessage(session);
msg.setSubject(subject);
msg.setText(message);
msg.setFrom(new InternetAddress(SENDER_ACCOUNT));
Transport transport = session.getTransport("smtp");
transport.connect();
transport.sendMessage(msg, new InternetAddress[]{new InternetAddress(direction)});
transport.close();
return true;
} catch (NoSuchProviderException e) {
System.out.println("沒有找到郵件服務提供者: " + e.getMessage());
} catch (MessagingException e) {
System.out.println("郵件傳送過程中出現異常: " + e.getMessage());
e.printStackTrace();
}
return false;
}
}
4,注意
埠:
SSL加密:接收伺服器(IMAP)埠號為993,傳送伺服器(SMTP)埠號為465。
阿里遮蔽了25埠,只能用465傳送郵件,否則本地測試正常,上線阿里雲伺服器後失敗。