2
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package com.example.demo.common;
|
||||
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class EmailSenderService {
|
||||
private final JavaMailSender mailSender;
|
||||
private final EmailProperties props;
|
||||
|
||||
@Value("${spring.mail.username:}")
|
||||
private String mailUsername;
|
||||
|
||||
public EmailSenderService(JavaMailSender mailSender, EmailProperties props) {
|
||||
this.mailSender = mailSender;
|
||||
this.props = props;
|
||||
}
|
||||
|
||||
public void sendPlainText(String to, String subject, String content) {
|
||||
if (to == null || to.isBlank()) throw new IllegalArgumentException("收件人邮箱不能为空");
|
||||
if (subject == null) subject = "";
|
||||
if (content == null) content = "";
|
||||
try {
|
||||
MimeMessage message = mailSender.createMimeMessage();
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, false, "UTF-8");
|
||||
helper.setFrom(resolveFromAddress());
|
||||
helper.setTo(to.trim());
|
||||
helper.setSubject(composeSubject(subject));
|
||||
helper.setText(content, false);
|
||||
mailSender.send(message);
|
||||
} catch (IllegalStateException | IllegalArgumentException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("发送邮件失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private String composeSubject(String subject) {
|
||||
String prefix = props.getSubjectPrefix();
|
||||
if (prefix == null || prefix.isBlank()) return subject;
|
||||
return prefix + " " + subject;
|
||||
}
|
||||
|
||||
private String resolveFromAddress() {
|
||||
String from = props.getFrom();
|
||||
if (from == null || from.isBlank()) from = mailUsername;
|
||||
if (from == null || from.isBlank()) {
|
||||
throw new IllegalStateException("邮件服务未配置,请设置 MAIL_USERNAME/MAIL_PASSWORD 以及 MAIL_FROM 或 spring.mail.username");
|
||||
}
|
||||
return from.trim();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user