Java 发送邮件
Java 发送邮件通常使用 JavaMail API 或 Spring Boot 的邮件功能 来实现。常见的邮件协议包括:
- SMTP(Simple Mail Transfer Protocol) —— 发送邮件
- POP3 / IMAP —— 接收邮件(一般用于客户端)
1. JavaMail API 发送邮件
JavaMail API 是 Java 官方提供的邮件发送库,常用于 SMTP 发送邮件。
1.1 添加 JavaMail 依赖
如果使用 Maven,需添加 javax.mail 依赖:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
或者 Jakarta Mail(新版支持):
<dependency>
<groupId>org.eclipse.angus</groupId>
<artifactId>angus-mail</artifactId>
<version>2.0.2</version>
</dependency>
1.2 使用 JavaMail 发送邮件
下面示例使用 SMTP 通过 Gmail 发送邮件。
步骤
- 配置 SMTP 服务器
- 创建
Session对象 - 发送
MimeMessage邮件
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class EmailSender {
public static void main(String[] args) {
String host = "smtp.gmail.com"; // SMTP 服务器地址
String username = "your-email@gmail.com"; // 发送邮箱
String password = "your-password"; // 应用专用密码(Gmail 需要)
String toEmail = "recipient@example.com"; // 收件人邮箱
// 1. 配置 SMTP 服务器属性
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587"); // Gmail SMTP 端口号
// 2. 创建 Session
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 3. 创建邮件内容
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
message.setSubject("Java 发送邮件测试");
message.setText("你好,这是一封通过 JavaMail API 发送的测试邮件!");
// 4. 发送邮件
Transport.send(message);
System.out.println("邮件发送成功!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
1.3 发送带附件的邮件
可以使用 MimeMultipart 发送 带附件的邮件:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import java.io.File;
public class EmailWithAttachment {
public static void main(String[] args) throws Exception {
String host = "smtp.gmail.com";
String username = "your-email@gmail.com";
String password = "your-password";
String toEmail = "recipient@example.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
message.setSubject("带附件的 Java 邮件");
// 创建邮件内容
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("你好,请查看附件!");
// 添加附件
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(new File("path/to/file.pdf")); // 本地文件路径
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("邮件发送成功!");
}
}
2. 使用 Spring Boot 发送邮件
Spring Boot 通过 Spring Mail 简化了 JavaMail API 操作,适用于企业应用开发。
2.1 添加 Spring Boot 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.2 配置邮件 SMTP
在 application.properties 或 application.yml 中添加邮件服务器配置:
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
2.3 发送简单邮件
创建 EmailService 发送邮件:
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 EmailService {
@Autowired
private JavaMailSender mailSender;
public void sendSimpleEmail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("your-email@gmail.com");
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
System.out.println("邮件发送成功!");
}
}
调用:
@Autowired
private EmailService emailService;
emailService.sendSimpleEmail("recipient@example.com", "测试邮件", "你好,这是 Spring Boot 发送的邮件!");
2.4 发送带附件的邮件
Spring Mail 也支持 附件发送:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
public void sendEmailWithAttachment(String to, String subject, String text, String filePath) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom("your-email@gmail.com");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
// 添加附件
File file = new File(filePath);
helper.addAttachment(file.getName(), file);
mailSender.send(message);
System.out.println("邮件发送成功!");
}
}
调用:
emailService.sendEmailWithAttachment("recipient@example.com", "带附件的邮件", "你好,请查收附件!", "path/to/file.pdf");
3. 总结
| 方式 | 适用场景 | 主要特点 |
|---|---|---|
| JavaMail API | 适用于所有 Java 项目 | 灵活但需要手动管理配置 |
| Spring Mail | Spring Boot 项目 | 简单易用,集成度高 |
| SMTP 发送 | 发送普通邮件 | 适用于大多数场景 |
| 带附件邮件 | 发送文件、PDF | 需要 MimeMultipart |
如果你的项目是 Spring Boot,建议使用 Spring Mail,代码简洁,集成度高。🚀
更多详细内容请关注其他相关文章。