本文目录导读:

我来为您详细介绍Java邮件推送功能的开发步骤和完整案例。
添加依赖
Maven项目(pom.xml)
<!-- JavaMail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<!-- Spring Boot Starter Mail (如果使用Spring Boot) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
基础邮件发送实现
1 纯文本邮件
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SimpleMailSender {
public static void sendTextEmail() throws MessagingException {
// 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. 创建Session
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your_email@qq.com", "authorization_code");
}
});
// 3. 创建邮件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your_email@qq.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recipient@example.com"));
message.setSubject("测试邮件");
message.setText("这是一封测试邮件!");
// 4. 发送邮件
Transport.send(message);
System.out.println("邮件发送成功!");
}
}
2 HTML格式邮件
public class HtmlMailSender {
public static void sendHtmlEmail() throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.qq.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your_email@qq.com", "authorization_code");
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your_email@qq.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recipient@example.com"));
message.setSubject("HTML格式邮件");
// 创建HTML内容
String htmlContent = "<html><body>"
+ "<h1>Hello!</h1>"
+ "<p>这是一封 <b>HTML</b> 格式的邮件。</p>"
+ "<p>当前时间:" + new java.util.Date() + "</p>"
+ "</body></html>";
message.setContent(htmlContent, "text/html; charset=UTF-8");
Transport.send(message);
System.out.println("HTML邮件发送成功!");
}
}
3 带附件邮件
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
public class AttachmentMailSender {
public static void sendWithAttachment() throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.qq.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your_email@qq.com", "authorization_code");
}
});
// 创建邮件
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your_email@qq.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recipient@example.com"));
message.setSubject("带附件的邮件");
// 创建邮件体
Multipart multipart = new MimeMultipart();
// 添加文本内容
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("请查收附件", "UTF-8");
multipart.addBodyPart(textPart);
// 添加附件
MimeBodyPart attachmentPart = new MimeBodyPart();
DataSource source = new FileDataSource("path/to/your/file.pdf");
attachmentPart.setDataHandler(new DataHandler(source));
attachmentPart.setFileName("document.pdf");
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("带附件邮件发送成功!");
}
}
Spring Boot集成实现
1 配置文件(application.yml)
spring:
mail:
host: smtp.qq.com
port: 587
username: your_email@qq.com
password: authorization_code # 授权码
protocol: smtp
properties:
mail:
smtp:
auth: true
starttls:
enable: true
connectiontimeout: 5000
timeout: 5000
writetimeout: 5000
2 邮件服务类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
// 发送简单文本邮件
public void sendSimpleEmail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
// 发送HTML邮件
public void sendHtmlEmail(String to, String subject, String htmlContent)
throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlContent, true); // true表示HTML格式
mailSender.send(message);
}
// 发送带附件的邮件
public void sendEmailWithAttachment(String to, String subject,
String content, File attachment)
throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
helper.addAttachment(attachment.getName(), attachment);
mailSender.send(message);
}
// 发送批量邮件
public void sendBulkEmails(String[] toList, String subject, String content) {
for (String to : toList) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
}
}
3 邮件模板工具类
import java.util.Map;
public class EmailTemplateUtil {
public static String buildWelcomeEmail(String username) {
return "<!DOCTYPE html>" +
"<html>" +
"<head><meta charset='UTF-8'></head>" +
"<body>" +
"<div style='background-color: #f4f4f4; padding: 20px;'>" +
"<h2>欢迎 " + username + "!</h2>" +
"<p>感谢您在[公司名称]注册账号。</p>" +
"<p>请点击以下链接激活您的账号:</p>" +
"<a href='http://example.com/activate?token=xxx'>激活账号</a>" +
"</div>" +
"</body>" +
"</html>";
}
public static String buildResetPasswordEmail(String resetLink) {
return "<!DOCTYPE html>" +
"<html>" +
"<head><meta charset='UTF-8'></head>" +
"<body>" +
"<div style='background-color: #f4f4f4; padding: 20px;'>" +
"<h3>密码重置请求</h3>" +
"<p>我们收到您的密码重置请求。</p>" +
"<p>请点击以下链接重置密码(24小时内有效):</p>" +
"<a href='" + resetLink + "'>重置密码</a>" +
"<p>如果您没有请求重置密码,请忽略此邮件。</p>" +
"</div>" +
"</body>" +
"</html>";
}
}
4 Controller示例
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/email")
public class EmailController {
@Autowired
private EmailService emailService;
@PostMapping("/send")
public String sendEmail(@RequestParam String to,
@RequestParam String subject,
@RequestParam String content) {
try {
emailService.sendSimpleEmail(to, subject, content);
return "邮件发送成功";
} catch (Exception e) {
return "邮件发送失败: " + e.getMessage();
}
}
@PostMapping("/send-html")
public String sendHtmlEmail(@RequestParam String to,
@RequestParam String subject,
@RequestParam String htmlContent) {
try {
emailService.sendHtmlEmail(to, subject, htmlContent);
return "HTML邮件发送成功";
} catch (Exception e) {
return "邮件发送失败: " + e.getMessage();
}
}
}
注意事项
1 邮箱配置
- 需要开启SMTP服务
- 使用授权码而非登录密码
- 常见邮箱SMTP配置:
| 邮箱 | SMTP服务器 | SSL端口 | TLS端口 |
|---|---|---|---|
| QQ邮箱 | smtp.qq.com | 465 | 587 |
| 163邮箱 | smtp.163.com | 465 | 25 |
| Gmail | smtp.gmail.com | 465 | 587 |
2 异常处理建议
@ExceptionHandler(MessagingException.class)
public ResponseEntity<String> handleMailException(MessagingException e) {
// 记录日志
logger.error("邮件发送失败", e);
// 返回错误信息
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("邮件发送失败: " + e.getMessage());
}
3 异步发送(推荐)
@Async
public CompletableFuture<Boolean> sendEmailAsync(String to, String subject, String content) {
try {
sendSimpleEmail(to, subject, content);
return CompletableFuture.completedFuture(true);
} catch (Exception e) {
return CompletableFuture.completedFuture(false);
}
}
这个实现包含了基本的邮件发送功能、Spring Boot集成、模板使用和最佳实践,根据实际需求,您可以进一步扩展功能,如邮件队列、重试机制等。