前言
在企业应用开发中,发送邮件是一个非常常见的需求,比如用户注册验证、密码重置、系统通知等场景。springboot 3提供了完善的邮件发送支持,本文将详细介绍如何在springboot 3中实现邮件发送功能,并提供最佳实践建议。
1. 环境准备
- jdk 17+
- springboot 3.0+
- maven/gradle
2. 项目配置
2.1 添加依赖
在 pom.xml中添加以下依赖:
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-mail</artifactid>
</dependency>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-thymeleaf</artifactid>
</dependency>2.2 配置邮件服务器
在 application.yml中添加邮件服务器配置:
spring:
mail:
host: smtp.qq.com # qq邮件服务器地址
port: 587 # 端口号
username: ${username}
password: ${password} # 需要去qq邮箱开通开通pop3/imap服务,并设置专用密码
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
thymeleaf:
cache: true
check-template: true
check-template-location: true
content-type: text/html
enabled: true
encoding: utf-8
excluded-view-names: ''
mode: html
prefix: classpath:/templates/
suffix: .html3. 代码实现
3.1 创建邮件服务接口
package com.example.springboot3email.service;
import org.springframework.web.multipart.multipartfile;
/**
* @author coderjia
* @create 2024/11/21 10:22
* @description
**/
public interface iemailservice {
void sendsimpleemail(string to, string subject, string text);
void sendhtmlemail(string to, string subject, string htmlcontent);
void sendemailwithattachment(string to, string subject, string text, multipartfile attachment);
}3.2 实现邮件服务
package com.example.springboot3email.service;
import jakarta.annotation.resource;
import jakarta.mail.internet.mimemessage;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.value;
import org.springframework.core.io.filesystemresource;
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 java.io.file;
/**
* @author coderjia
* @create 2024/11/21 10:23
* @description
**/
@service
@slf4j
public class emailserviceimpl implements iemailservice {
@resource
private javamailsender mailsender;
@value("${spring.mail.username}")
private string from;
/**
* 发送简单文本邮件
*
* @param to
* @param subject
* @param text
*/
@override
public void sendsimpleemail(string to, string subject, string text) {
try {
simplemailmessage message = new simplemailmessage();
message.setfrom(from);
message.setto(to);
message.setsubject(subject);
message.settext(text);
mailsender.send(message);
log.info("simple email sent successfully to: {}", to);
} catch (exception e) {
log.error("failed to send simple email", e);
throw new runtimeexception("failed to send email", e);
}
}
/**
* 发送html格式的邮件
*
* @param to
* @param subject
* @param htmlcontent
*/
@override
public void sendhtmlemail(string to, string subject, string htmlcontent) {
try {
mimemessage message = mailsender.createmimemessage();
mimemessagehelper helper = new mimemessagehelper(message, true, "utf-8");
helper.setfrom(from);
helper.setto(to);
helper.setsubject(subject);
helper.settext(htmlcontent, true);
mailsender.send(message);
log.info("html email sent successfully to: {}", to);
} catch (exception e) {
log.error("failed to send html email", e);
throw new runtimeexception("failed to send email", e);
}
}
/**
* 发送带附件的邮件
*
* @param to
* @param subject
* @param text
* @param attachment
*/
@override
public void sendemailwithattachment(string to, string subject, string text, multipartfile attachment) {
try {
mimemessage message = mailsender.createmimemessage();
mimemessagehelper helper = new mimemessagehelper(message, true, "utf-8");
helper.setfrom(from);
helper.setto(to);
helper.setsubject(subject);
helper.settext(text);
// 创建临时文件
file tempfile = file.createtempfile("upload_", attachment.getoriginalfilename());
attachment.transferto(tempfile);
// 使用 filesystemresource 包装临时文件
filesystemresource file = new filesystemresource(tempfile);
helper.addattachment(attachment.getoriginalfilename(), file);
mailsender.send(message);
log.info("email with attachment sent successfully to: {}", to);
// 删除临时文件
tempfile.delete();
} catch (exception e) {
log.error("failed to send email with attachment", e);
throw new runtimeexception("failed to send email", e);
}
}
}3.3 创建邮件模板
在 resources/templates目录下创建html模板 emailtemplate.html(使用thymeleaf):
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>email template</title>
</head>
<body>
<h1>welcome, <span th:text="${name}">user</span>!</h1>
<p>this is a sample email template using thymeleaf.</p>
<p>your verification code is: <strong th:text="$[code]">123456</strong></p>
</body>
</html>
3.4 使用模板发送邮件
@service
public class templateemailservice {
@autowired
private emailservice emailservice;
@autowired
private templateengine templateengine;
public void sendtemplateemail(string to, string subject, string templatename, map<string, object> variables) {
context context = new context();
variables.foreach(context::setvariable);
string htmlcontent = templateengine.process(templatename, context);
emailservice.sendhtmlemail(to, subject, htmlcontent);
}
}
4. 最佳实践建议
4.1 异步发送
为避免邮件发送影响主业务流程,建议使用异步方式发送邮件:
@configuration
@enableasync
public class asyncconfig implements asyncconfigurer {
@override
public executor getasyncexecutor() {
threadpooltaskexecutor executor = new threadpooltaskexecutor();
executor.setcorepoolsize(5);
executor.setmaxpoolsize(10);
executor.setqueuecapacity(25);
executor.setthreadnameprefix("emailasync-");
executor.initialize();
return executor;
}
}
@service
public class asyncemailservice {
@async
public completablefuture<void> sendemailasync(string to, string subject, string content) {
// 邮件发送逻辑
return completablefuture.completedfuture(null);
}
}
4.2 重试机制
实现邮件发送重试机制:
@service
public class retryableemailservice {
@retryable(value = {messagingexception.class},
maxattempts = 3,
backoff = @backoff(delay = 1000))
public void sendemailwithretry(string to, string subject, string content) {
// 邮件发送逻辑
}
@recover
public void recover(messagingexception e, string to) {
// 处理最终失败的情况
log.error("failed to send email after retries", e);
}
}
4.3 邮件发送限流
使用令牌桶算法实现邮件发送限流:
@service
public class ratelimitedemailservice {
private final ratelimiter ratelimiter = ratelimiter.create(10.0); // 每秒10封邮件
public void sendemailwithratelimit(string to, string subject, string content) {
if (ratelimiter.tryacquire()) {
// 发送邮件
} else {
throw new runtimeexception("rate limit exceeded");
}
}
}
4.4 邮件发送记录
记录邮件发送历史:
@entity
@table(name = "email_log")
public class emaillog {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
private string to;
private string subject;
private localdatetime sendtime;
private emailstatus status;
private string errormessage;
// getters and setters
}
5. 安全性建议
- 不要在代码中硬编码邮件服务器凭证
- 使用环境变量或配置中心存储敏感信息
- 实现邮件发送频率限制,防止滥用
- 记录邮件发送日志,便于问题排查
- 使用tls/ssl加密传输
- 定期轮换邮件服务器密码
6. 测试示例
package com.example.springboot3email.controller;
import com.example.springboot3email.service.iemailservice;
import com.example.springboot3email.service.templateemailservice;
import jakarta.annotation.resource;
import lombok.extern.slf4j.slf4j;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.multipart.multipartfile;
import java.util.hashmap;
import java.util.map;
/**
* @author coderjia
* @create 2024/11/21 10:32
* @description
**/
@slf4j
@restcontroller
public class emailcontroller {
@resource
private iemailservice emailservice;
@resource
private templateemailservice templateemailservice;
// 发送简单文本邮件接口
@postmapping("/sendsimpleemail")
public string sendsimpleemail(@requestparam("to") string to,
@requestparam("subject") string subject,
@requestparam("text") string text) {
emailservice.sendsimpleemail(to, subject, text);
return "success";
}
// 发送html邮件接口
@postmapping("/sendhtmlemail")
public string sendhtmlemail(@requestparam("to") string to,
@requestparam("subject") string subject,
@requestparam("htmlcontent") string htmlcontent) {
emailservice.sendhtmlemail(to, subject, htmlcontent);
return "success";
}
// 发送带附件的邮件接口
@postmapping("/sendemailwithattachment")
public string sendemailwithattachment(@requestparam("to") string to,
@requestparam("subject") string subject,
@requestparam("text") string text,
@requestparam("attachment") multipartfile attachment) {
emailservice.sendemailwithattachment(to, subject, text, attachment);
return "success";
}
// 发送模板邮件接口
@postmapping("/sendtemplateemail")
public string sendtemplateemail(@requestparam("to") string to,
@requestparam("subject") string subject,
@requestparam("templatename") string templatename) {
map<string, object> variables = new hashmap<>();
variables.put("name", "coderjia");
variables.put("code", 12530);
templateemailservice.sendtemplateemail(to, subject, templatename, variables);
return "success";
}
}
发送效果
普通邮件

html邮件

带附件邮件

模板邮件

7. 常见问题解决
7.1 连接超时
spring:
mail:
properties:
mail:
smtp:
connectiontimeout: 5000
timeout: 5000
writetimeout: 5000
7.2 ssl证书问题
spring:
mail:
properties:
mail:
smtp:
ssl:
trust: "*"
7.3 中文乱码
helper.setfrom(new internetaddress(from, "发件人名称", "utf-8"));
8. 总结
本文详细介绍了在springboot 3中实现邮件发送功能的完整解决方案,包括基本配置、代码实现、最佳实践、安全建议等内容。通过采用异步发送、重试机制、限流等最佳实践,可以构建一个健壮的邮件发送系统。在实际应用中,要根据具体需求选择合适的实现方式,同时注意安全性和性能的平衡。
到此这篇关于重学springboot3之如何发送email邮件功能的文章就介绍到这了,更多相关springboot3发送email内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论