cn.stylefeng.roses.email.spring.SpringJavaSender Maven / Gradle / Ivy
package cn.stylefeng.roses.email.spring;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.roses.email.MailSender;
import cn.stylefeng.roses.email.spring.enums.SpringMailSendResultEnum;
import cn.stylefeng.roses.email.spring.exception.SpringMailException;
import cn.stylefeng.roses.email.spring.model.SendMailParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
/**
* java默认的邮件发送方式实现
*
* @author fengshuonan
* @date 2018-07-08-下午3:34
*/
@Slf4j
public class SpringJavaSender implements MailSender {
/**
* spring的发送器
*/
private final JavaMailSender javaMailSender;
/**
* 发送邮件的地址
*/
private final String from;
public SpringJavaSender(JavaMailSender javaMailSender, String from) {
this.javaMailSender = javaMailSender;
this.from = from;
}
@Override
public void sendMail(SendMailParam sendMailParam) {
//校验发送邮件的参数
assertSendMailParams(sendMailParam);
//spring发送邮件
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(sendMailParam.getTo());
mimeMessageHelper.setSubject(sendMailParam.getTitle());
mimeMessageHelper.setText(sendMailParam.getContent(), true);
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
log.error("发送邮件异常", e);
throw new SpringMailException(SpringMailSendResultEnum.MAIL_SEND_ERROR.getCode(), SpringMailSendResultEnum.MAIL_SEND_ERROR.getMessage());
}
}
/**
* 校验发送邮件的请求参数
*
* @author fengshuonan
* @Date 2018/7/8 下午6:41
*/
private void assertSendMailParams(SendMailParam sendMailParam) {
if (sendMailParam == null) {
throw new SpringMailException(400, "请求参数为空");
}
if (ObjectUtil.isEmpty(sendMailParam.getTo())) {
throw new SpringMailException(400, "收件人邮箱为空");
}
if (ObjectUtil.isEmpty(sendMailParam.getTitle())) {
throw new SpringMailException(400, "邮件标题为空");
}
if (ObjectUtil.isEmpty(sendMailParam.getContent())) {
throw new SpringMailException(400, "邮件内容为空");
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy