import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String[] args) {
// 邮件服务器配置
String host = "smtp.example.com"; // SMTP服务器地址
String port = "587"; // SMTP服务器端口
String username = "your-email@example.com"; // 发件人邮箱
String password = "your-password"; // 发件人密码
// 收件人邮箱
String to = "recipient@example.com";
// 邮件主题
String subject = "Test Email";
// 邮件内容
String body = "This is a test email sent from Java.";
// 设置邮件服务器属性
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
// 创建会话
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建邮件消息对象
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setText(body);
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
System.out.println("Failed to send email.");
}
}
}
Properties
对象设置邮件服务器的相关属性,如认证、TLS加密等。Session.getInstance
方法创建一个邮件会话,并通过Authenticator
类提供用户名和密码进行身份验证。MimeMessage
类创建邮件消息对象,设置发件人、收件人、主题和邮件正文。Transport.send
方法发送邮件,并处理可能发生的异常。如果上述代码不能满足需求,请根据具体的邮件服务提供商(如Gmail、QQ邮箱等)调整SMTP服务器地址、端口和其他相关配置。
上一篇:java字符串转map
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站