import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
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", "yourpassword");
}
});
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.* 和 javax.mail.internet.* 是用于发送电子邮件的核心包。Properties 类配置 SMTP 服务器的主机名、端口号、认证方式和 TLS 启用等信息。Session 对象:使用 Session.getDefaultInstance 方法创建一个默认的会话对象,并提供认证信息(用户名和密码)。MimeMessage 对象:使用会话对象创建一个 MimeMessage 实例,设置发件人、收件人、主题和邮件内容。Transport.send 方法发送邮件,并在控制台输出成功信息。如果需要更复杂的邮件功能(如附件、HTML 内容等),可以进一步扩展 MimeMessage 的设置。
上一篇:java timer
下一篇:java运算符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站