在Java程序中发送电子邮件通常依赖于JavaMail API。JavaMail API是Java的一部分,用于发送和接收电子邮件。以下是一个使用JavaMail API发送简单电子邮件的基本步骤和示例代码。
步骤 1: 添加JavaMail依赖
首先,确保你的项目中包含了JavaMail的依赖。如果你正在使用Maven,可以在你的pom.xml
文件中添加以下依赖:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version> <!-- 请检查是否有更新的版本 -->
</dependency>
步骤 2: 编写发送邮件的代码
以下是一个简单的Java程序,用于发送一封电子邮件:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
// 发件人电子邮箱
final String from = "your-email@example.com";
// 授权码(不是邮箱密码),在邮箱设置中生成
final String password = "your-email-password-or-app-password";
// 指定发送邮件的主机为 smtp.example.com
String host = "smtp.example.com";
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "587"); // SMTP端口
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true"); // 启用TLS
// 获取默认的 Session 对象。
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
try {
// 创建默认的 MimeMessage 对象。
MimeMessage message = new MimeMessage(session);
// Set From: header field
message.setFrom(new InternetAddress(from));
// Set To: header field
message.addRecipient(Message.RecipientType.TO, new InternetAddress("to-email@example.com"));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// 现在设置实际消息
message.setText("This is actual message");
// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
注意事项
-
授权码:对于大多数现代邮件服务(如Gmail, Outlook等),你需要生成一个“应用密码”或“授权码”而不是直接使用你的邮箱密码。这可以在你的邮箱帐户的“安全性”或“应用密码”设置中找到。
-
SMTP服务器地址和端口:不同的邮件服务商有不同的SMTP服务器地址和端口。请根据你的邮件服务商查找正确的信息。
-
错误处理:上面的示例中只进行了基本的错误处理(打印堆栈跟踪)。在生产环境中,你可能需要更复杂的错误处理逻辑。
-
TLS/SSL:大多数现代邮件服务器要求使用TLS或SSL进行安全通信。在上面的示例中,我们使用了TLS(
mail.smtp.starttls.enable="true"
)。 -
发送HTML邮件:如果你想要发送HTML格式的邮件,可以使用
message.setContent()
方法并设置适当的MIME类型(text/html
)。
确保你的防火墙和网络设置允许你的应用访问SMTP服务器。