本文目录导读:

我来为您提供一个完整的Java发送邮件案例,包括基础版和增强版(支持附件和HTML内容)。
准备工作
添加依赖(Maven)
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<!-- 或使用最新版本 -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
邮箱设置
以QQ邮箱为例:
- 开启SMTP服务
- 获取授权码(不是QQ密码)
基础版:发送纯文本邮件
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SendEmailSimple {
public static void main(String[] args) {
// 收件人邮箱
String to = "recipient@example.com";
// 发件人邮箱
String from = "your-email@qq.com";
// QQ邮箱授权码
String password = "your-authorization-code";
// 1. 配置邮件服务器参数
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.qq.com"); // SMTP服务器
props.put("mail.smtp.port", "587"); // SMTP端口
props.put("mail.smtp.auth", "true"); // 需要认证
props.put("mail.smtp.starttls.enable", "true"); // 启用TLS
// 2. 创建认证器
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
};
// 3. 创建会话
Session session = Session.getInstance(props, auth);
try {
// 4. 创建邮件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from)); // 发件人
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to)); // 收件人
message.setSubject("测试邮件"); // 主题
// 5. 设置邮件内容
message.setText("这是一封来自Java的测试邮件!\nHello, this is a test email!");
// 6. 发送邮件
Transport.send(message);
System.out.println("邮件发送成功!");
} catch (MessagingException e) {
e.printStackTrace();
System.out.println("邮件发送失败:" + e.getMessage());
}
}
}
增强版:发送HTML邮件(支持图片、附件)
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.Properties;
public class SendEmailAdvanced {
/**
* 发送HTML格式邮件,支持附件和图片
*/
public static void sendHtmlEmail() {
// 邮箱配置
String host = "smtp.qq.com";
String port = "587";
final String username = "your-email@qq.com";
final String password = "your-authorization-code";
// 收件人
String to = "recipient@example.com";
// 配置SMTP
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.connectiontimeout", 5000); // 连接超时
props.put("mail.smtp.timeout", 5000); // 读取超时
// 创建会话
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
// 开启调试模式
session.setDebug(true);
try {
// 创建邮件
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject("HTML格式邮件测试", "UTF-8");
// 创建多功能消息
Multipart multipart = new MimeMultipart("related");
// ============ 1. HTML正文 ============
MimeBodyPart htmlPart = new MimeBodyPart();
String htmlContent =
"<html>" +
"<head>" +
"<meta charset='UTF-8'>" +
"<style>" +
"body { font-family: Arial, sans-serif; }" +
"h1 { color: #333; }" +
".highlight { color: #ff6600; font-weight: bold; }" +
"table {border-collapse: collapse;}" +
"td, th {border: 1px solid #ccc; padding: 10px;}" +
"</style>" +
"</head>" +
"<body>" +
"<h1>邮件标题</h1>" +
"<p class='highlight'>这是一封使用Java发送的HTML格式邮件!</p>" +
"<p>支持样式:</p>" +
"<ul>" +
"<li>文本格式</li>" +
"<li>表格</li>" +
"<li>图片(cid引用)</li>" +
"</ul>" +
// 引用图片
"<img src='cid:myImage' alt='我的图片' width='200' height='150'>" +
"<br><br>" +
"<table>" +
"<tr><th>姓名</th><th>年龄</th><th>城市</th></tr>" +
"<tr><td>张三</td><td>25</td><td>北京</td></tr>" +
"<tr><td>李四</td><td>30</td><td>上海</td></tr>" +
"</table>" +
"<br>" +
"<a href='https://www.example.com'>点击访问网站</a>" +
"</body></html>";
htmlPart.setContent(htmlContent, "text/html;charset=UTF-8");
multipart.addBodyPart(htmlPart);
// ============ 2. 内嵌图片 ============
// 如果有图片,可以这样添加
/*
MimeBodyPart imagePart = new MimeBodyPart();
DataSource source = new FileDataSource("/path/to/image.jpg");
imagePart.setDataHandler(new DataHandler(source));
imagePart.setHeader("Content-ID", "<myImage>");
imagePart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(imagePart);
*/
// ============ 3. 附件 ============
// 添加附件示例
/*
MimeBodyPart attachmentPart = new MimeBodyPart();
DataSource fileSource = new FileDataSource("/path/to/file.pdf");
attachmentPart.setDataHandler(new DataHandler(fileSource));
attachmentPart.setFileName(MimeUtility.encodeText("附件文件.pdf"));
multipart.addBodyPart(attachmentPart);
*/
// 附加示例:添加一个文本附件
MimeBodyPart attachmentText = new MimeBodyPart();
attachmentText.setText("这是一份附件文档的内容");
attachmentText.setFileName("附件.txt");
multipart.addBodyPart(attachmentText);
// 设置邮件内容
message.setContent(multipart);
// 发送邮件
Transport.send(message);
System.out.println("HTML邮件发送成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
sendHtmlEmail();
}
}
工具类封装
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
/**
* 邮件发送工具类
*/
public class EmailUtil {
// 配置信息
private static final String HOST = "smtp.qq.com";
private static final String PORT = "587";
private static final String USERNAME = "your-email@qq.com";
private static final String PASSWORD = "your-authorization-code";
/**
* 发送简单文本邮件
*/
public static void sendSimpleEmail(String to, String subject, String content) {
sendEmail(to, subject, content, false);
}
/**
* 发送HTML邮件
*/
public static void sendHtmlEmail(String to, String subject, String htmlContent) {
sendEmail(to, subject, htmlContent, true);
}
/**
* 统一发送方法
*/
private static void sendEmail(String to, String subject, String content, boolean isHtml) {
Properties props = new Properties();
props.put("mail.smtp.host", HOST);
props.put("mail.smtp.port", PORT);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USERNAME, PASSWORD);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(USERNAME));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject, "UTF-8");
if (isHtml) {
message.setContent(content, "text/html;charset=UTF-8");
} else {
message.setText(content);
}
Transport.send(message);
System.out.println("邮件发送成功至:" + to);
} catch (MessagingException e) {
System.out.println("邮件发送失败至:" + to);
e.printStackTrace();
}
}
/**
* 批量发送
*/
public static void sendBatch(String[] recipients, String subject, String content) {
for (String recipient : recipients) {
sendSimpleEmail(recipient, subject, content);
}
}
}
// 使用示例
public class EmailTest {
public static void main(String[] args) {
// 发送简单邮件
EmailUtil.sendSimpleEmail(
"user@example.com",
"测试邮件",
"这是一封测试邮件内容"
);
// 发送HTML邮件
String html = "<h1>欢迎加入</h1><p>感谢您的注册!</p>";
EmailUtil.sendHtmlEmail(
"user@example.com",
"注册确认",
html
);
}
}
常见邮箱配置
| 邮箱 | SMTP服务器 | 端口 | 注意事项 |
|---|---|---|---|
| QQ邮箱 | smtp.qq.com | 587/465 | 需要授权码 |
| 163邮箱 | smtp.163.com | 25/465 | 需要授权码 |
| Gmail | smtp.gmail.com | 587 | 需要应用专用密码 |
| Outlook | smtp.office365.com | 587 | 需要企业邮箱 |
注意事项
- 授权码安全:不要将授权码硬编码在代码中,建议使用配置文件或环境变量
- 发送限制:大多数邮箱有每日发送限制
- 编码问题需要设置UTF-8编码
- 异步发送:生产环境建议使用异步方式发送邮件
# application.properties 配置示例 mail.host=smtp.qq.com mail.port=587 mail.username=your-email@qq.com mail.password=your-auth-code mail.properties.mail.smtp.auth=true mail.properties.mail.smtp.starttls.enable=true
这个案例涵盖了Java邮件发送的常见场景,您可以根据实际需求进行调整和使用。