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";
// 邮箱授权码或密码
final String username = "sender@example.com"; // 用户名
final String password = "your-email-password"; // 授权码
// SMTP服务器信息
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(username, 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 包来处理邮件发送。to 和 from 变量,分别表示收件人和发件人的邮箱地址。host)、端口 (port)、认证 (auth) 和 TLS (starttls)。Session.getDefaultInstance 方法创建一个 Session 对象,并提供认证信息。Transport.send 方法发送邮件。MessagingException 异常。上一篇:java set 转 list
下一篇:java网络编程技术
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站