Java

java发送邮件怎么实现

小亿
109
2023-08-04 23:10:14
栏目: 编程语言

要实现Java发送邮件,可以使用JavaMail API。以下是一个简单的示例代码,演示了如何使用JavaMail API发送邮件:

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendMail {
public static void main(String[] args) {
// 发件人邮箱地址
String from = "your-email@example.com";
// 发件人邮箱密码或授权码
String password = "your-password";
// 收件人邮箱地址
String to = "recipient-email@example.com";
// 设置邮件属性
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.example.com");
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() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
try {
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("JavaMail API Test");
message.setText("Hello, This is a test email from JavaMail API.");
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}

在上面的示例代码中,请确保将以下变量替换为实际的值:

运行上述代码,将会使用JavaMail API发送一封包含文本内容的测试邮件。如果一切正常,你将在控制台上看到"Email sent successfully."的输出。

0
看了该问题的人还看了