在Java开发中,操作邮箱发送邮件是一项常见的需求,例如系统通知、密码重置、营销推广等场景,Java提供了多种方式实现邮件发送功能,其中使用JavaMail API是较为传统且稳定的选择,结合Spring框架则能进一步简化开发流程,本文将详细介绍基于JavaMail和Spring Boot的邮件发送实现方法,包括环境准备、核心配置、代码实现及常见问题处理。

环境准备与依赖配置
在使用Java操作邮箱发送邮件前,需确保项目中引入必要的依赖,以Maven项目为例,若采用JavaMail原生API,需添加以下依赖:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
若使用Spring Boot框架,则可通过spring-boot-starter-mail简化配置,该依赖已自动集成JavaMail API:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.7.0</version>
</dependency>
邮箱服务器配置
邮件发送依赖于邮箱服务商的SMTP服务器,需提前开启SMTP服务并获取授权码(以QQ邮箱为例:登录QQ邮箱→设置→账户→POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务→开启“IMAP/SMTP服务”并生成授权码),在Spring Boot项目中,配置文件application.yml中需添加以下参数:

spring:
mail:
host: smtp.qq.com # SMTP服务器地址
port: 587 # 端口号(QQ邮箱为587,SSL加密时为465)
username: your-email@qq.com # 发件人邮箱
password: your-authorization-code # 邮箱授权码(非登录密码)
protocol: smtp # 传输协议
properties:
mail:
smtp:
auth: true # 启用SMTP认证
starttls:
enable: true # 启用TLS加密
基于JavaMail API的邮件发送实现
创建邮件会话
通过Session对象配置邮件发送属性,并创建Transport实例建立与SMTP服务器的连接:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class JavaMailSender {
public static void sendTextEmail(String to, String subject, String content) throws MessagingException {
// 配置邮件会话属性
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.qq.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
// 创建认证对象
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email@qq.com", "your-authorization-code");
}
};
// 获取邮件会话
Session session = Session.getInstance(props, auth);
// 创建邮件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your-email@qq.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setText(content);
// 发送邮件
Transport.send(message);
}
}
发送复杂邮件(HTML/附件)
若需发送HTML格式邮件或带附件的邮件,可使用MimeMessage并设置MimeMultipart
public static void sendMultiPartEmail(String to, String subject, String htmlContent, String filePath)
throws MessagingException {
Session session = Session.getInstance(getProperties(), new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email@qq.com", "your-authorization-code");
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("your-email@qq.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
// 创建 multipart 对象
Multipart multipart = new MimeMultipart();
// 添加HTML内容
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlContent, "text/html;charset=UTF-8");
multipart.addBodyPart(htmlPart);
// 添加附件
if (filePath != null) {
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(new File(filePath));
multipart.addBodyPart(attachmentPart);
}
message.setContent(multipart);
Transport.send(message);
}
基于Spring Boot的邮件发送实现
Spring Boot对邮件发送进行了封装,通过JavaMailSender接口可简化操作,首先在配置文件中添加邮箱配置(如前文所述),然后注入JavaMailSender实例:
发送简单文本邮件
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class SpringMailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("your-email@qq.com"); // 发件人(需与配置文件一致)
message.setTo(to);
message.setSubject(subject);
message.setText(content);
javaMailSender.send(message);
}
}
发送HTML邮件及附件
使用MimeMessageHelper简化复杂邮件的构建:

import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
@Service
public class SpringMailService {
@Resource
private JavaMailSender javaMailSender;
public void sendHtmlMail(String to, String subject, String htmlContent, String filePath)
throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom("your-email@qq.com");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlContent, true); // 第二个参数表示HTML格式
if (filePath != null) {
helper.addAttachment("附件名", new File(filePath)); // 添加附件
}
javaMailSender.send(message);
}
}
常见问题与解决方案
- 认证失败:检查邮箱授权码是否正确,确保SMTP服务已开启。
- 连接超时:确认网络是否可访问SMTP服务器,或调整超时时间(
mail.smtp.timeout配置)。 - 中文乱码:在设置邮件内容时指定字符集(如
UTF-8),HTML邮件需设置Content-Type为text/html;charset=UTF-8。 - 附件发送失败:检查文件路径是否正确,确保文件未被占用或过大(部分邮箱对附件大小有限制,如QQ邮箱支持最大50MB)。
Java操作邮箱发送邮件的核心是依赖JavaMail API,而Spring Boot通过自动配置和封装进一步提升了开发效率,开发者可根据项目需求选择原生API或Spring集成方式,注意配置SMTP服务器参数、处理异常场景及编码问题,掌握邮件发送功能后,可轻松实现系统通知、用户交互等业务场景,提升应用的用户体验。


















