springboot整合别的框架,发送邮件的种类有很多,本文章使用的是JavaMailSender。实现了邮件发送主机的灵活配置,配置信息从数据库获取,然后动态加载;附件文件的一个或多个的发送;文本样式化处理。
本次使用的springboot版本是3.2.4;jdk版本是17
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.4</version>
<relativePath/>
</parent>
<groupId>com.bonc</groupId>
<artifactId>sendEmail</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sendEmail</name>
<packaging>jar</packaging>
<description>sendEmail</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>17</java.version>
<mybatisplus.version>3.5.7</mybatisplus.version>
<mybatis.version>3.0.3</mybatis.version>
<mysql.version>9.0.0</mysql.version>
<druid.version>1.2.23</druid.version>
<hutool.version>5.8.32</hutool.version>
<lombok.version>1.18.34</lombok.version>
</properties>
<dependencies>
<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>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatisplus.version}</version>
<exclusions>
<exclusion>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
</exclusion>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;
import java.util.Properties;
/**
* 邮件发送服务
* 附件可以没有,也可以是一个或多个
*/
@Service
@Slf4j
public class EmailServiceImpl implements EmailService {
@Resource
private TbSendEmailInfoService tbSendEmailInfoService;
@Resource
private TbSendEmailLogDao tbSendEmailLogDao;
@Override
public String sendMail(MultipartFile[] multipartFiles, EmailRequest emailRequest) {
String msg = null;
msg = checkRequestParam(emailRequest);
if(!ObjectUtils.isEmpty(msg)){
return msg;
}
TbSendEmailInfoEntity emailInfo = tbSendEmailInfoService.lambdaQuery()
.eq(TbSendEmailInfoEntity::getSendSys, emailRequest.getSendSys())
.one();
if(emailInfo == null){
return emailRequest.getSendSys()+"系统的配置不存在,请配置";
}
//创建一个JavaMailSenderImpl对象
JavaMailSenderImpl jms = this.buildJavaMailSenderImpl(emailInfo);
//1.创建一个邮箱对象
MimeMessage message = jms.createMimeMessage();
// MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message,true);
//邮件收件人 1或多个
helper.setTo(emailRequest.getSendTo().split(","));
if(!ObjectUtils.isEmpty(emailRequest.getCcTo())){
helper.setCc(emailRequest.getCcTo().split(","));
}
helper.setFrom(emailInfo.getSendFrom());
//邮件主题
helper.setSubject(emailRequest.getSubject());
//邮件内容
helper.setText(emailRequest.getText(),true);
//邮件发送时间
helper.setSentDate(new Date());
if(multipartFiles!=null && multipartFiles.length > 0){
for (int i = 0; i < multipartFiles.length; i++) {
helper.addAttachment(multipartFiles[i].getOriginalFilename(), FileUtil.convert(multipartFiles[i]));
}
}
jms.send(message);
msg = "邮件发送成功";
log.info("发送邮件成功:{}",emailRequest.getSendTo());
} catch (Exception e) {
log.error("发送邮件时发生异常!",e);
msg = "邮件发送失败"+e.getMessage();
}
//插入发送日志信息
this.buildSendMsg(emailRequest,emailInfo.getSendId(),msg);
return msg;
}
private void buildSendMsg(EmailRequest emailRequest, Long sendId, String msg) {
TbSendEmailLogEntity logEntity = new TbSendEmailLogEntity();
logEntity.setSendId(sendId);
logEntity.setSendSubject(emailRequest.getSubject());
logEntity.setSendTo(emailRequest.getSendTo());
logEntity.setSendCc(emailRequest.getCcTo());
logEntity.setSendSts(msg.contains("成功") ? "0":"1");
logEntity.setSendMsg(msg);
logEntity.setSendTime(new Date());
tbSendEmailLogDao.insert(logEntity);
}
private JavaMailSenderImpl buildJavaMailSenderImpl(TbSendEmailInfoEntity emailInfo) {
//创建一个JavaMailSenderImpl对象
JavaMailSenderImpl jms = new JavaMailSenderImpl();
//服务器名
jms.setHost(emailInfo.getSendHost());
//网易账号
jms.setUsername(emailInfo.getSendUser());
//授权码
jms.setPassword(emailInfo.getSendPwd());
//设置编码防止乱码
jms.setDefaultEncoding("utf-8");
Properties p = new Properties();
p.setProperty("mail.smtp.ssl.enable", "true");
p.setProperty("mail.smtp.ssl.required", "false");
p.setProperty("mail.debug", "true");
jms.setJavaMailProperties(p);
return jms;
}
private String checkRequestParam(EmailRequest emailRequest) {
StringBuilder msg = new StringBuilder();
if(ObjectUtils.isEmpty(emailRequest.getSendSys())){
msg.append("发送系统不能为空");
}
if(ObjectUtils.isEmpty(emailRequest.getSendTo())){
msg.append("接收人不能为空");
}
if(ObjectUtils.isEmpty(emailRequest.getSubject())){
msg.append("发送主题不能为空");
}
if(ObjectUtils.isEmpty(emailRequest.getText())){
msg.append("发送内容不能为空");
}
return msg.toString();
}
}
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
public class FileUtil {
public static File convert(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
try (InputStream in = file.getInputStream();
OutputStream out = new FileOutputStream(convFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
return convFile;
}
}