Skip to content

Instantly share code, notes, and snippets.

@kang8
Last active August 17, 2021 10:07
Show Gist options
  • Save kang8/67e03361d8cf7658b1ea7c55084b2045 to your computer and use it in GitHub Desktop.
Save kang8/67e03361d8cf7658b1ea7c55084b2045 to your computer and use it in GitHub Desktop.
使用 com.sun.mail:jakarta.mail:1.6.7 包来发送邮件

选择包

使用 Java 发邮件,最常用的应该就是 com.sun.mail:javax.mail 这个包了。但该仓库已经归档,最新的版本 1.6.7 已经是 2018 年事了。

于是另外寻找,看到最新的 Spring Boot 中使用 com.sun.mail:jakarta.mail 这个包。还在稳定更新。于是就选择该包的最新版

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>jakarta.mail</artifactId>
    <version>1.6.7</version>
</dependency>

发送邮件

注意:发送邮件与包的选择没有关系。SMTP 是 Java EE 的一个标准,引入的包只是其中的一个实现,只要面对接口编程即可。

发送一个邮件可以分成三部分:

  1. 准备邮件的基本属性。如服务器地址、端口、是否加密等。(该信息可以放到 application.yml 中以便于修改。)
  2. 根据上面准备的属性生成 Session,并使用用户名和密码授权登录。
  3. 利用 Session 创建 MimeMessage,并将要发送的消息 setting 到对应的属性上。
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Properties;
public class SMPTUtils {
/**
* 使用 163 举例
*/
private static final String HOST = "smtp.163.com";
private static final String PORT = "587";
private static final String USERNAME = "@163.com";
private static final String PASSWORD = "";
private static final String MIMETYPE_TEXT_HTML_UTF_8 = "text/html; charset=utf-8";
private static Properties prepareProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", HOST);
props.put("mail.smtp.port", PORT);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
return props;
}
private static Session createSession() {
Properties prop = prepareProperties();
return Session.getInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USERNAME, PASSWORD);
}
});
}
public static void sendMail(List<String> primaryRecipients, List<String> carbonCopyRecipients, String subject, String content) throws MessagingException {
Session session = createSession();
session.setDebug(true);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(USERNAME));
setRecipientsByList(message, Message.RecipientType.TO, primaryRecipients);
setRecipientsByList(message, Message.RecipientType.CC, carbonCopyRecipients);
message.setSubject(subject, StandardCharsets.UTF_8.name());
message.setContent(content, MIMETYPE_TEXT_HTML_UTF_8);
Transport.send(message);
}
private static void setRecipientsByList(MimeMessage message, Message.RecipientType type, List<String> recipients) throws MessagingException {
if (recipients == null) {
return;
}
for (String recipient : recipients) {
message.setRecipient(type, new InternetAddress(recipient));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment