📌 目录
- Java 发送邮件简介
- Java 邮件发送所需的库
- 配置 SMTP 服务器
- Java 邮件发送示例
- 4.1 使用
JavaMail
发送简单文本邮件 - 4.2 发送 HTML 格式的邮件
- 4.3 附加附件的邮件
- 4.1 使用
- Java 邮件发送常见问题
- 总结
- 参考资料
- 出站链接
1. Java 发送邮件简介
在 Java 中,可以使用 JavaMail API 来发送电子邮件。JavaMail 是一个提供发送、接收和处理邮件的 API,它支持不同的邮件协议(如 SMTP、IMAP 和 POP3),使得 Java 应用程序能够与邮件服务器进行交互,完成邮件的发送与接收。
2. Java 邮件发送所需的库
为了发送邮件,您需要使用 JavaMail
API 和 Activation
库。可以通过以下步骤将这些库添加到项目中:
- 通过 Maven 添加依赖
如果你使用 Maven 管理项目,可以在 pom.xml
文件中添加以下依赖:
<dependencies>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
- 手动下载 JAR 包
您也可以从 JavaMail官网 下载相关的 JAR 包,手动将其添加到项目的类路径中。
3. 配置 SMTP 服务器
在发送邮件之前,需要配置邮件服务器的 SMTP(简单邮件传输协议)信息。不同的邮件服务提供商有不同的 SMTP 服务器地址和端口:
- Gmail:
- SMTP 服务器:
smtp.gmail.com
- 端口:
587
- SMTP 服务器:
- Outlook/Hotmail:
- SMTP 服务器:
smtp-mail.outlook.com
- 端口:
587
- SMTP 服务器:
- Yahoo:
- SMTP 服务器:
smtp.mail.yahoo.com
- 端口:
465
- SMTP 服务器:
确保配置了正确的 SMTP 服务器,并且启用了发送邮件所需的权限(例如,对于 Gmail,您可能需要允许“低安全性应用”访问)。
4. Java 邮件发送示例
4.1 使用 JavaMail
发送简单文本邮件
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) {
String to = "recipient@example.com";
String from = "your-email@example.com";
String host = "smtp.gmail.com";
final String username = "your-email@example.com"; // 邮箱账号
final String password = "your-email-password"; // 邮箱密码
// 配置邮件服务器的属性
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// 获取默认的 Session 对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(from));
// 设置收件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 设置邮件主题
message.setSubject("Test Email");
// 设置邮件正文
message.setText("This is a test email sent from Java.");
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
在这个示例中,我们使用了 Gmail 的 SMTP 服务器来发送邮件。代码设置了邮件的发件人、收件人、主题和正文内容,并通过 Transport.send()
方法发送邮件。
4.2 发送 HTML 格式的邮件
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SendHtmlEmail {
public static void main(String[] args) {
String to = "recipient@example.com";
String from = "your-email@example.com";
String host = "smtp.gmail.com";
final String username = "your-email@example.com";
final String password = "your-email-password";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("HTML Email Test");
// 设置邮件内容为 HTML
String htmlContent = "<h1>This is an HTML email</h1><p>This email contains <b>HTML</b> content.</p>";
message.setContent(htmlContent, "text/html");
// 发送邮件
Transport.send(message);
System.out.println("HTML email sent successfully.");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
在此示例中,我们通过 message.setContent()
方法设置了 HTML 格式的邮件内容。
4.3 附加附件的邮件
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.Properties;
public class SendEmailWithAttachment {
public static void main(String[] args) {
String to = "recipient@example.com";
String from = "your-email@example.com";
String host = "smtp.gmail.com";
final String username = "your-email@example.com";
final String password = "your-email-password";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Email with Attachment");
// 创建邮件正文
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("Please find the attachment.");
// 创建附件
MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource source = new FileDataSource("path/to/your/file.txt");
attachmentPart.setDataHandler(new DataHandler(source));
attachmentPart.setFileName("file.txt");
// 将正文和附件添加到邮件中
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(textPart);
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
// 发送邮件
Transport.send(message);
System.out.println("Email with attachment sent successfully.");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
这个示例展示了如何将文件作为附件添加到邮件中。MimeMultipart
用于将邮件正文和附件一起打包发送。
5. Java 邮件发送常见问题
- 身份验证失败:请确保提供的用户名和密码正确,并且已经为邮箱启用了 SMTP 访问权限。例如,对于 Gmail,需要在账户中启用“低安全性应用”访问。
- 端口配置错误:请根据您的邮件服务提供商,确保端口号正确。例如,Gmail 使用端口 587,而其他服务可能有所不同。
- 防火墙或安全策略问题:某些防火墙可能会阻止应用程序连接到 SMTP 服务器,确保网络设置没有问题。
6. 总结
使用 Java 发送邮件非常简单,借助 JavaMail
API,您可以轻松地发送文本邮件、HTML 格式邮件以及带附件的邮件。在使用 Java 发送邮件时,确保正确配置 SMTP 服务器地址和端口,且有适当的身份验证信息。
发表回复