在项目开发中,偶尔会遇到一些业务需要使用到发送邮件的功能,比如在一些平台上面会以邮箱作为用户标识进行注册,然后找回密码也会选择使用邮箱的方案,这里总结了几种常见的使用java代码发送邮件的方案:
/* 发送邮件(方案1): <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency> */ /* 发送邮件(方案2): <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> */ /* 发送邮件(方案3): 使用Apache Commons Email <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.5</version> </dependency> */ /* 发送邮件(方案4): JavaMail API <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> */ /* 发送邮件(方案5): 使用Thymeleaf与Spring Boot结合发送HTML邮件 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> */ 话不多说,上代码:
package com.cetide.demo.control;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.SimpleEmail;
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.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
@Controller
public class EmailController {
/*
发送邮件(方案1):
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
*/
public void sendMailByJavaxEmail(String email,String code){
try {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//配置邮箱信息
Properties props = System.getProperties();
//邮件服务器
props.setProperty("mail.smtp.host", "smtp.qq.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
//邮件服务器端口
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
//鉴权信息
props.setProperty("mail.smtp.auth", "true");
//建立邮件会话
Session session = Session.getDefaultInstance(props, new Authenticator() {
//身份认证
protected PasswordAuthentication getPasswordAuthentication() {
//1.账户 授权码
return new PasswordAuthentication("1147683258@qq.com", "bsfyppqvhrqqecgj");
}
});
//建立邮件对象
MimeMessage message = new MimeMessage(session);
//设置邮件的发件人
message.setFrom(new InternetAddress("1147683258@qq.com"));
//2.设置邮件的收件人
message.setRecipients(Message.RecipientType.TO, email);
//设置邮件的主题
message.setSubject("来自Cetide网的信息");
//文本部分
message.setContent("收到您的登录请求发送验证码"+code, "text/html;charset=UTF-8");
message.saveChanges();
//发送邮件
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
发送邮件(方案2):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
*/
//spring:
// mail:
// host: smtp.example.com # SMTP 服务器地址
// port: 587 # SMTP 端口号
// username: your-email@example.com # 邮箱账户
// password: your-password # 邮箱密码
// properties:
// mail:
// smtp:
// auth: true
// starttls.enable: true # 启用 STARTTLS
@Autowired
private JavaMailSender mailSender;
public void sendErrorEmail(String message) {
try {
SimpleMailMessage email = new SimpleMailMessage();
email.setTo("admin@example.com"); // 管理员邮箱
email.setSubject("Database Initialization Error");
email.setText("An error occurred during database initialization:\n" + message);
mailSender.send(email);
System.out.println("Error email sent successfully.");
} catch (Exception e) {
System.err.println("Failed to send error email: " + e.getMessage());
}
}
/*
发送邮件(方案3):
使用Apache Commons Email
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
*/
// 发送简单的文本邮件
public void sendSimpleEmail(String subject, String message, String toEmail) {
try {
// 创建SimpleEmail对象并设置基本信息
SimpleEmail email = new SimpleEmail();
email.setHostName("smtp.example.com"); // 设置SMTP服务器地址
email.setSmtpPort(587); // SMTP服务器端口
email.setAuthentication("your_email@example.com", "your_password"); // SMTP用户名和密码
email.setSSLOnConnect(true); // 启用SSL
// 设置邮件的发送人、收件人、主题和内容
email.setFrom("your_email@example.com", "Your Name"); // 发件人地址和姓名
email.addTo(toEmail); // 收件人地址
email.setSubject(subject); // 邮件主题
email.setMsg(message); // 邮件内容
// 发送邮件
email.send();
System.out.println("Email sent successfully to " + toEmail);
} catch (EmailException e) {
e.printStackTrace();
System.err.println("Failed to send email: " + e.getMessage());
}
}
// 发送HTML邮件的示例
public void sendHtmlEmail(String subject, String htmlMessage, String toEmail) {
try {
// 创建HtmlEmail对象并设置基本信息
HtmlEmail email = new HtmlEmail();
email.setHostName("smtp.example.com"); // 设置SMTP服务器地址
email.setSmtpPort(587); // SMTP服务器端口
email.setAuthentication("your_email@example.com", "your_password"); // SMTP用户名和密码
email.setSSLOnConnect(true); // 启用SSL
// 设置邮件的发送人、收件人、主题和内容
email.setFrom("your_email@example.com", "Your Name"); // 发件人地址和姓名
email.addTo(toEmail); // 收件人地址
email.setSubject(subject); // 邮件主题
email.setHtmlMsg(htmlMessage); // 邮件内容(HTML格式)
// 发送邮件
email.send();
System.out.println("HTML Email sent successfully to " + toEmail);
} catch (EmailException e) {
e.printStackTrace();
System.err.println("Failed to send HTML email: " + e.getMessage());
}
}
/*
发送邮件(方案4):
JavaMail API
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
*/
private final String smtpHost = "smtp.example.com"; // SMTP 服务器地址
private final int smtpPort = 587; // SMTP 端口
private final String username = "your_email@example.com"; // 发送邮箱
private final String password = "your_password"; // 邮箱密码
public void sendSimpleEmailBySunMail(String toEmail, String subject, String messageText) {
// 配置邮件会话属性
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", smtpHost);
properties.put("mail.smtp.port", smtpPort);
// 创建会话对象
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username, password);
}
});
try {
// 创建邮件对象
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
message.setSubject(subject);
message.setText(messageText);
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully to " + toEmail);
} catch (MessagingException e) {
e.printStackTrace();
System.err.println("Failed to send email: " + e.getMessage());
}
}
public void sendHtmlEmailBySunMail(String toEmail, String subject, String htmlContent) {
// 配置邮件会话属性
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", smtpHost);
properties.put("mail.smtp.port", smtpPort);
// 创建会话对象
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username, password);
}
});
try {
// 创建邮件对象
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
message.setSubject(subject);
message.setContent(htmlContent, "text/html");
// 发送邮件
Transport.send(message);
System.out.println("HTML Email sent successfully to " + toEmail);
} catch (MessagingException e) {
e.printStackTrace();
System.err.println("Failed to send HTML email: " + e.getMessage());
}
}
/*
发送邮件(方案5):
使用Thymeleaf与Spring Boot结合发送HTML邮件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
*/
@GetMapping("/sendThymeleafEmail")
public String sendThymeleafEmail(@RequestParam String toEmail) {
sendHtmlEmail(toEmail, "Test Thymeleaf Email", "John Doe", "This is a test email using Thymeleaf.");
return "Thymeleaf email sent successfully to " + toEmail;
}
@Autowired
private TemplateEngine templateEngine;
public void sendHtmlEmail(String toEmail, String subject, String name, String message) {
try {
// 创建MimeMessage对象
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
// 设置邮件发送人、收件人、主题
helper.setFrom("your_email@example.com");
helper.setTo(toEmail);
helper.setSubject(subject);
// 创建邮件的 HTML 内容
Context context = new Context();
context.setVariable("name", name);
context.setVariable("message", message);
String htmlContent = templateEngine.process("email-template", context);
// 设置邮件内容
helper.setText(htmlContent, true);
// 发送邮件
mailSender.send(mimeMessage);
System.out.println("HTML email sent successfully to " + toEmail);
} catch (MessagingException e) {
e.printStackTrace();
System.err.println("Failed to send HTML email: " + e.getMessage());
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Email</title>
</head>
<body>
<h1 th:text="'Hello, ' + ${name} + '!'">Hello, John!</h1>
<p>We wanted to let you know about an important update:</p>
<p th:text="${message}">This is a sample email message.</p>
<p>Thank you!</p>
</body>
</html>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>