仅供参考:实现逻辑自行修改
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
yml配置
---
spring:
mail:
protocol: smtp
host: 邮件服务器地址
port: 465
username: 你的QQ邮箱
sendFrom: 发件人【需要邮箱】
password: 秘钥/授权码
default-encoding: UTF-8
properties:
mail:
debug: false
smtp:
socketFactory:
class: javax.net.ssl.SSLSocketFactory
工具类
import cn.hutool.core.io.IoUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Objects;
@Slf4j
public class MeetingEmailUtils {
private static final JavaMailSender mailSender;
private static final String sendFrom;
private static final String defaultSubject;
static {
mailSender = SpringUtil.getBean(JavaMailSender.class);
sendFrom = SpringUtil.getProperty("spring.mail.sendFrom");
defaultSubject = SpringUtil.getProperty("spring.mail.defaultSubject");
}
public static void sendMail(String to, String subject, String content, List<JSONObject> fileArrays, String... ccTos) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
if (StringUtils.isBlank(to)) {
throw new RuntimeException("邮箱收件人为空");
}
try {
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setFrom(sendFrom);
messageHelper.setTo(to);
if (Objects.nonNull(ccTos) && ccTos.length == 0) {
messageHelper.setCc(ccTos);
}
messageHelper.setSubject(StringUtils.isNotBlank(subject) ? subject : defaultSubject);
if (StringUtils.isNotBlank(content)) {
messageHelper.setText(content);
}
if (Objects.nonNull(fileArrays) && !fileArrays.isEmpty()) {
for (JSONObject json : fileArrays) {
InputStreamSource inputStreamSource = () -> IoUtil.toStream(json.getBytes("fileBytes"));
messageHelper.addAttachment(json.getString("fileName"), inputStreamSource);
}
}
mailSender.send(mimeMessage);
} catch (Exception e) {
log.error("发送给【{}】的邮件失败,原因是: {}", to, e.getMessage());
}
log.info("邮件批量发送完成");
}
}