温馨提示×

java实现发送邮件代码怎么写

小亿
94
2023-09-22 18:24:41
栏目: 编程语言

Java实现发送邮件的代码可以使用JavaMail库来完成。以下是一个简单的示例代码:

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) {
// 发送方邮箱地址
String fromEmail = "your_email@example.com";
// 发送方邮箱密码或授权码
String password = "your_password";
// 接收方邮箱地址
String toEmail = "recipient_email@example.com";
// 配置SMTP服务器的属性
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// 创建Session对象
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
});
try {
// 创建MimeMessage对象
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(fromEmail));
// 设置收件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
// 设置邮件主题
message.setSubject("Test Email");
// 设置邮件内容
message.setText("This is a test email.");
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}

请注意,你需要将代码中的"your_email@example.com",“your_password”,“smtp.example.com”,"recipient_email@example.com"替换为你自己的邮箱地址、密码、SMTP服务器地址和接收方邮箱地址。

0