package com.product.admin.util.email;
|
|
import java.io.File;
|
import java.util.Properties;
|
|
import javax.mail.MessagingException;
|
import javax.mail.internet.MimeMessage;
|
|
import org.springframework.core.io.FileSystemResource;
|
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
import org.springframework.mail.javamail.MimeMessageHelper;
|
|
import com.product.admin.config.CmnConst;
|
import com.product.core.entity.FieldSetEntity;
|
import com.product.core.exception.BaseException;
|
|
/**
|
* smtp邮件发送工具类
|
* Copyright LX-BASE
|
* @Title: LX-BASE-
|
* @Project: SendMailThread
|
* @Date: 2020-09-29 16:36
|
* @Author: 杜洪波
|
* @Description:
|
*/
|
public class SmtpSendMail {
|
|
|
private static JavaMailSenderImpl mailSender;
|
|
/**
|
* spring-boot包发送邮件
|
* @param attachment 附件路径
|
* @param staffInfo 收件人信息
|
* @return
|
* @throws MessagingException
|
* @throws BaseException
|
*/
|
public static void sendMail(FieldSetEntity fseMailInfo,String attachment) throws BaseException {
|
|
mailSender = new JavaMailSenderImpl();
|
mailSender.setHost(fseMailInfo.getString(CmnConst.SMTP_SERVER_HOST));//链接服务器
|
mailSender.setUsername(fseMailInfo.getString(CmnConst.SMTP_USERNAME));//账号
|
mailSender.setPassword(fseMailInfo.getString(CmnConst.SMTP_LICENSE_CODE));//授权码
|
mailSender.setDefaultEncoding("UTF-8");//默认编码
|
|
Properties properties = new Properties();
|
properties.setProperty("mail.smtp.auth", "true");//开启认证
|
properties.setProperty("mail.smtp.socketFactory.port", fseMailInfo.getString(CmnConst.SMTP_SERVER_PORT));//设置ssl端口
|
properties.setProperty("mail.smtp.socketFactory.port", "465");//设置ssl端口
|
properties.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
|
mailSender.setJavaMailProperties(properties);
|
|
try {
|
MimeMessage message=mailSender.createMimeMessage();
|
MimeMessageHelper helper;
|
|
helper = new MimeMessageHelper(message,true,"UTF-8");
|
|
//设置发件人
|
helper.setFrom(fseMailInfo.getString(CmnConst.SMTP_USERNAME));
|
//设置收件人
|
helper.setTo(fseMailInfo.getString("addressee"));
|
//设置邮件主题
|
helper.setSubject(fseMailInfo.getString("mail_title"));
|
//设置邮件内容
|
helper.setText(fseMailInfo.getString("mail_content"),true);
|
//装载附件
|
if (attachment!=null && !"".equals(attachment)) {
|
String[]attachArray=attachment.split(",");
|
for (Object filepath:attachArray) {
|
FileSystemResource fileSystemResource = new FileSystemResource(new File((String) filepath));
|
String fileName = fileSystemResource.getFilename();
|
helper.addAttachment(fileName,fileSystemResource);
|
}
|
}
|
//发送邮件
|
mailSender.send(message);
|
fseMailInfo.setValue("send_stat", 1);
|
} catch (Exception e) {
|
fseMailInfo.setValue("send_stat", 2);
|
fseMailInfo.setValue("failure_reason", e.getMessage());
|
}
|
}
|
}
|