Commit e9aa8ae5 by zhangxingmin

配置

parent b8bb7b32
......@@ -27,11 +27,19 @@
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- 邮箱依赖 -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>${email.version}</version>
</dependency>
<!-- XXL-Job 核心依赖 -->
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
</dependency>
</dependencies>
</project>
package com.yd.email.service.handler;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class MailSendJobHandler extends IJobHandler {
@Autowired
private MailService mailService;
@Autowired
private MailTaskMapper mailTaskMapper;
@Autowired
private MailRecipientMapper mailRecipientMapper;
@Override
public ReturnT<String> execute(String param) throws Exception {
log.info("开始执行邮件发送任务,参数: {}", param);
Long taskId = Long.parseLong(param);
MailTask mailTask = mailTaskMapper.selectById(taskId);
if (mailTask == null) {
return new ReturnT<>(ReturnT.FAIL_CODE, "邮件任务不存在");
}
// 更新任务状态为发送中
mailTask.setStatus(1);
mailTaskMapper.updateById(mailTask);
try {
// 查询所有收件人
List<MailRecipient> recipients = mailRecipientMapper.selectByTaskId(taskId);
int successCount = 0;
int failCount = 0;
for (MailRecipient recipient : recipients) {
try {
List<String> ccList = recipient.getCcAddresses() != null ?
Arrays.asList(recipient.getCcAddresses().split(",")) :
new ArrayList<>();
mailService.sendMail(
mailTask.getFromAddress(),
recipient.getToAddress(),
ccList,
mailTask.getSubject(),
mailTask.getContent(),
mailTask.getAttachmentPath()
);
// 更新发送状态
recipient.setSendStatus(1);
recipient.setSendTime(new Date());
mailRecipientMapper.updateById(recipient);
successCount++;
} catch (Exception e) {
log.error("发送邮件失败: {}", recipient.getToAddress(), e);
recipient.setSendStatus(2);
recipient.setErrorMsg(e.getMessage());
mailRecipientMapper.updateById(recipient);
failCount++;
}
}
// 更新任务状态
mailTask.setStatus(failCount == 0 ? 2 : 3); // 全部成功为2,有失败为3
mailTaskMapper.updateById(mailTask);
log.info("邮件发送任务完成: 成功{}个, 失败{}个", successCount, failCount);
return new ReturnT<>("发送完成: 成功" + successCount + "个, 失败" + failCount + "个");
} catch (Exception e) {
log.error("邮件发送任务执行异常", e);
mailTask.setStatus(3);
mailTaskMapper.updateById(mailTask);
return new ReturnT<>(ReturnT.FAIL_CODE, "任务执行异常: " + e.getMessage());
}
}
}
\ No newline at end of file
package com.yd.email.service.service;
public interface EmailService {
}
package com.yd.email.service.service.impl;
import com.yd.email.service.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;
/**
* 邮件服务实现类
*/
@Service
@Slf4j
public class EmailServiceImpl implements EmailService {
@Value("${spring.mail.host}") // 从配置文件中注入邮件服务器主机地址
private String host;
@Value("${spring.mail.username}") // 从配置文件中注入发件人用户名
private String username;
@Value("${spring.mail.password}") // 从配置文件中注入发件人密码
private String password;
// @Autowired // 自动注入邮件任务Mapper(数据库操作接口)
// private MailTaskMapper mailTaskMapper;
//
// @Autowired // 自动注入邮件收件人Mapper(数据库操作接口)
// private MailRecipientMapper mailRecipientMapper;
// 发送邮件的主要方法
public void sendMail(String from, String to, List<String> cc, String subject,
String content, String attachmentPath) throws Exception {
// 创建邮件配置属性对象
Properties props = new Properties();
// 设置SMTP需要身份验证
props.put("mail.smtp.auth", "true");
// 启用TLS加密传输
props.put("mail.smtp.starttls.enable", "true");
// 设置邮件服务器主机名
props.put("mail.smtp.host", host);
// 设置邮件服务器端口号(587是TLS标准端口)
props.put("mail.smtp.port", "587");
// 创建邮件会话对象,传入配置和认证器
Session session = Session.getInstance(props, new Authenticator() {
// 重写获取密码认证的方法
protected PasswordAuthentication getPasswordAuthentication() {
// 返回用户名密码认证对象
return new PasswordAuthentication(username, password);
}
});
// 使用try-catch块处理邮件发送异常
try {
// 创建MIME类型邮件消息对象
Message message = new MimeMessage(session);
// 设置发件人地址
message.setFrom(new InternetAddress(from));
// 设置收件人地址(支持多个收件人,用逗号分隔)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
// 判断是否有抄送人
if (cc != null && !cc.isEmpty()) {
// 将抄送人列表转换为逗号分隔的字符串
String ccAddresses = String.join(",", cc);
// 设置抄送人地址
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccAddresses));
}
// 设置邮件主题
message.setSubject(subject);
// 设置邮件发送时间(当前时间)
message.setSentDate(new Date());
// 创建邮件正文部分
MimeBodyPart messageBodyPart = new MimeBodyPart();
// 设置正文内容,指定HTML格式和UTF-8编码
messageBodyPart.setContent(content, "text/html;charset=utf-8");
// 创建多部分内容容器(用于组合正文和附件)
Multipart multipart = new MimeMultipart();
// 将正文部分添加到多部分容器中
multipart.addBodyPart(messageBodyPart);
// 判断是否有附件路径
if (StringUtils.isNotBlank(attachmentPath)) {
// 创建附件部分
MimeBodyPart attachmentPart = new MimeBodyPart();
// 创建文件数据源
DataSource source = new FileDataSource(attachmentPath);
// 设置附件的数据处理器
attachmentPart.setDataHandler(new DataHandler(source));
// 设置附件文件名(使用原文件名)
attachmentPart.setFileName(new File(attachmentPath).getName());
// 将附件部分添加到多部分容器中
multipart.addBodyPart(attachmentPart);
}
// 将多部分内容设置为邮件的完整内容
message.setContent(multipart);
// 发送邮件
Transport.send(message);
// 记录成功日志
log.info("邮件发送成功: {} -> {}", from, to);
} catch (MessagingException e) {
// 记录失败日志,包含异常信息
log.error("邮件发送失败: {} -> {}", from, to, e);
// 抛出运行时异常
throw new RuntimeException("邮件发送失败: " + e.getMessage());
}
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment