import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
// 收件人电子邮件地址
String to = "recipient@example.com";
// 发件人电子邮件地址
String from = "sender@example.com";
// 发送邮件的服务器信息
String host = "smtp.example.com";
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// 获取默认会话对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("sender@example.com", "password");
}
});
try {
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// 设置 From: 头部头字段
message.setFrom(new InternetAddress(from));
// 设置 To: 头部头字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 设置 Subject: 头部头字段
message.setSubject("This is the Subject Line!");
// 设置实际邮件文本
message.setText("This is actual message");
// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
javax.mail
包中的类,用于处理邮件发送的相关操作。Properties
类设置 SMTP 服务器的主机名、端口号,并启用 TLS 加密和身份验证。Session
对象:使用 Session.getDefaultInstance
方法创建一个会话对象,并提供了一个 Authenticator
实现来处理身份验证。MimeMessage
对象:创建一个 MimeMessage
对象来构建邮件内容,包括发件人、收件人、主题和正文。Transport.send
方法发送邮件,并在控制台输出发送成功的提示信息。上一篇:java long object longvalue
下一篇:java map遍历的三种方式
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站