@Service
public class EmailUtil {
@Autowired
private JavaMailSender mailSender;
/**
* 用来发送模版邮件
*/
@Autowired
private TemplateEngine templateEngine;
@Value("${spring.mail.username}")
private String from;
@Async
public void sendEmail(Context context, String templateName, String to, String [] cc,
String subject, String text, List<String> attachmentList){
try {
// 解决附件名称过长导致的附件名称乱码问题
System.setProperty("mail.mime.splitlongparameters", "false");
// 定义邮件信息
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
if(cc != null && cc.length > 0){
helper.setCc(cc);
}
// 如果存在模板,定义邮件模板中的内容,context的内容对应email.html的${project}占位的内容
if(context != null && StringUtils.isNotBlank(templateName)){
String emailContent = templateEngine.process(templateName, context);
helper.setText(emailContent, true);
}else{
helper.setText(text);
}
// 如果存在附件,定义邮件的附件
if(attachmentList != null && attachmentList.size() > 0){
for (String attachment : attachmentList) {
FileSystemResource file = new FileSystemResource(attachment);
helper.addAttachment(file.getFilename(), file);
}
}
mailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}