首先,你需要下载并导入JavaMail库。你可以从Oracle官方网站上找到相关资源。
你需要指定用于发送电子邮件的SMTP服务器的地址和端口。常见的SMTP服务器有Gmail(smtp.gmail.com),Outlook(smtp.office365.com)等。
String host = "smtp.gmail.com";
int port = 587;
创建一个Properties
对象来配置会话属性,包括SMTP服务器身份验证、TLS加密等。这些属性将传递给Session.getInstance()
方法来创建电子邮件会话。
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
使用之前设置的属性创建一个Session
对象。你需要提供发送者的电子邮件地址和密码来进行身份验证。
String senderEmail = "[email protected]";
String password = "your-password";
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmail, password);
}
});
使用MimeMessage
类创建电子邮件消息。设置发送者、接收者、主题和正文等。
String recipientEmail = "[email protected]";
String subject = "Test Email";
String messageContent = "This is a test email.";
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmail));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
message.setSubject(subject);
message.setText(messageContent);
使用Transport.send()
方法发送创建的消息。
Transport.send(message);
System.out.println("Email sent successfully.");
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSender {
public static void main(String[] args) {
String host = "smtp.gmail.com";
int port = 587;
String senderEmail = "[email protected]";
String password = "your-password";
String recipientEmail = "[email protected]";
String subject = "Test Email";
String messageContent = "This is a test email.";
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmail, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmail));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
message.setSubject(subject);
message.setText(messageContent);
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
请确保在运行代码之前,将[email protected]
替换为实际的发送者电子邮件地址,your-password
替换为发送者电子邮件的密码,并将[email protected]
替换为接收者的电子邮件地址。
另外,请注意,如果你使用的是Gmail或类似的服务提供商,可能需要在你的邮箱设置中启用“允许较低安全性应用程序访问”选项。