import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailUtil {
// 发送邮件的方法
public static void sendEmail(String host, String port, final String userName, final String password, String toAddress,
String subject, String message) throws AddressException, MessagingException {
// 设置邮件服务器的属性
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// 创建会话
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// 创建MimeMessage对象
MimeMessage mimeMessage = new MimeMessage(session);
// 设置发件人
mimeMessage.setFrom(new InternetAddress(userName));
// 设置收件人
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
// 设置邮件主题
mimeMessage.setSubject(subject);
// 设置邮件内容
mimeMessage.setText(message);
// 发送邮件
Transport.send(mimeMessage);
}
// 测试发送邮件
public static void main(String[] args) {
try {
String host = "smtp.example.com"; // SMTP服务器地址
String port = "587"; // SMTP服务器端口
String userName = "your-email@example.com"; // 发件人邮箱
String password = "your-password"; // 发件人密码
String toAddress = "recipient@example.com"; // 收件人邮箱
String subject = "Test Subject"; // 邮件主题
String message = "This is a test email."; // 邮件内容
sendEmail(host, port, userName, password, toAddress, subject, message);
System.out.println("Email sent successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Properties对象设置SMTP服务器的相关属性,如主机、端口、认证方式等。Authenticator类进行身份验证,并创建一个Session对象。MimeMessage类创建邮件对象,并设置发件人、收件人、主题和内容。Transport.send()方法发送邮件。上一篇:java urldecoder
下一篇:java格式化日期
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站