关注WX:CodingTechWork
介绍
概述
- 在一些业务功能中,发送邮件是必须的,比如告警通知、日报、月报等信息推送,都需要通过邮件服务器来发送邮件。
- JavaMail 是 Java 平台上用于处理电子邮件的 API,可以用于发送、接收和处理电子邮件。
配置
mail.smtp.host: SMTP 服务器主机名或 IP 地址。
mail.smtp.port: SMTP 服务器端口号,默认为 25。
mail.smtp.auth: 指定是否需要进行 SMTP 服务器身份验证,通常设置为 "true"。
mail.smtp.user: SMTP 服务器登录用户名。
mail.smtp.password: SMTP 服务器登录密码。
mail.smtp.connectiontimeout: 连接超时时间,以毫秒为单位。
mail.smtp.timeout: I/O 超时时间,以毫秒为单位。
mail.smtp.starttls.enable: 指定是否启用 STARTTLS 加密,通常设置为 "true"。
mail.smtp.starttls.required: 指定是否要求使用 STARTTLS 加密,通常设置为 "true"。
mail.smtp.ssl.enable: 指定是否启用 SSL 加密,通常设置为 "true"。
mail.smtp.ssl.protocols: 指定 SMTP 客户端使用的 SSL 协议版本。
mail.smtp.ssl.trust: 指定 SMTP 客户端信任的服务器证书的名称或别名。
mail.smtp.socketFactory.class: 指定自定义的 SocketFactory 类。
mail.smtp.socketFactory.fallback: 指定是否在创建 SSL 套接字失败时回退到普通套接字。
mail.smtp.socketFactory.port: 指定自定义 SocketFactory 类所使用的端口。
mail.debug: 是否启用调试模式,用于输出调试信息。
mail.mime.charset: 指定邮件的字符编码。
mail.smtp.connectionpoolsize: 指定连接池大小,用于控制与 SMTP 服务器的连接数。
代码模板
依赖
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
代码实现
package com.test.selfcoding.service;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class EmailSender {
public static void main(String[] args) {
String to = "recipient@example.com";
String cc = "cc@example.com";
String bcc = "bcc@example.com";
String from = "sender@example.com";
String host = "smtp.example.com";
String protocol = "smtp";
final String username = "user_name";
final String password = "user_password";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.transport.protocol", protocol);
properties.setProperty("mail.smtp.starttls.enabled", "true");
properties.setProperty("mail.smtp.starttls.required", "true");
properties.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc));
message.setSubject("This is the Subject Line!");
message.setText("This is test message");
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
运行结果
Sent message successfully....