import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) {
// 收件人电子邮箱
String to = "recipient@example.com";
// 发件人电子邮箱
String from = "sender@example.com";
// 发送邮件的 SMTP 服务器信息
String host = "smtp.example.com";
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "587");
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: 头部的 header 字段
message.setFrom(new InternetAddress(from));
// 设置 To: 头部的 header 字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 设置 Subject: 头部的 header 字段
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 对象设置邮件服务器的相关属性,如主机地址、端口、是否需要认证等。Session.getDefaultInstance 方法创建一个会话对象,并提供认证信息(用户名和密码)。MimeMessage 类创建邮件对象,并设置发件人、收件人、主题和邮件内容。Transport.send 方法发送邮件。MessagingException 异常。上一篇:java.net.unknownhostexception
下一篇:java 获取当前时间戳
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站