@PostMapping("/sendEmail")
public Result sendEmail(String id, String toEmail, String ccEmail) {
// 或 User obj = (User)session.getAttribute("currentUser");
User user = (User) SecurityUtils.getSubject().getPrincipal();
// TODO 获取信息
MailBean mailBean = MailBean.getMailBean();
Context context = new Context();
context.setVariable("detail", detail);
context.setVariable("user", user);
// String template:模板页面,例如“template.html”
String content = templateEngine.process(template, context);
mailBean.setSubject("xxx");
mailBean.setText(content);
Result result = mailUtil.sendMailTemplate(mailBean, toEmail.replaceAll(" ", "").split(";"), ccEmail.replaceAll(" ", "").split(";"), null, null, user);
// TODO 更改其他信息状态
return result;
}
/**
* 模板邮件发送
* @param mailBean 邮件类
* @param toEmails 收件人
* @param ccEmails 抄送人
* @param attachFiles 附件地址
*/
public Result sendMailTemplate(MailBean mailBean, String[] toEmails,String [] ccEmails, Map<String, String> attachFiles, Integer defaultFile, Map<String, String> inLine, User user) {
try {
setSMTPInfo(user);
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(mailSender.getUsername());//发送者
// 收件人设置默认
if (null == toEmails || toEmails.length == 0){
toEmails = new String[]{"xxx"};
}
helper.setTo(toEmails);//接收者
if (null != ccEmails && ccEmails.length > 0) {
helper.setCc(ccEmails);
}
helper.setSubject(mailBean.getSubject());//主题
helper.setText(mailBean.getText(), true);//邮件内容
if (null != attachFiles && !attachFiles.isEmpty()) {
String uploadFileName;
for (Map.Entry<String, String> filePath : attachFiles.entrySet()) {
if (StringUtils.isNotBlank(filePath.getKey()) && StringUtils.isNotBlank(filePath.getValue())) {
// 通过远程文件链接添加附件
if (StringUtils.startsWith(filePath.getKey(),"http")){
uploadFileName = filePath.getKey();
// 链接内包含xxx地址,需要转成location资源地址,否则报错找不到地址
if (uploadFileName.contains("xxx")){
uploadFileName = "https"+ uploadFileName.substring(4);
}else {
// URLEncoder.encode(url.lastIndexOf("/") + 1), "UTF-8") 空格url编码是+号,404找不到链接地址
// UriUtils.encode 空格会url编码成%20
uploadFileName = uploadFileName.substring(0, uploadFileName.lastIndexOf("/") + 1) + UriUtils.encode(uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1), "UTF-8");
}
URL fileUrl = new URL(uploadFileName);
HttpURLConnection urlCon = (HttpURLConnection) fileUrl.openConnection();
urlCon.setConnectTimeout(6000);
urlCon.setReadTimeout(6000);
int code = urlCon.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new Exception(filePath.getKey()+"文件读取失败");
}
InputStream in = urlCon.getInputStream();
helper.addAttachment(filePath.getValue(), new ByteArrayResource(IOUtils.toByteArray(in)));
}else { // 服务器本地文件添加附件
FileSystemResource file = new FileSystemResource(filePath.getKey());
helper.addAttachment(filePath.getValue(), file);
}
}
}
}
if (null != defaultFile && defaultFile < 0){
FileSystemResource file = new FileSystemResource("C:\\template\\export.xls");
helper.addAttachment("export.xls", file);
}
// 内联资源(静态资源):邮件需要确保先设置邮件正文,再设置内联资源相关信息
// 由于邮件服务商不同,可能有些邮件并不支持内联资源的展示;
// 在测试过程中,新浪邮件不支持,QQ邮件支持;
// 不支持不意味着邮件发送不成功,而且内联资源在邮箱内无法正确加载
if (!inLine.isEmpty()) {
for (Map.Entry<String, String> inLinePath : inLine.entrySet()) {
FileSystemResource res = new FileSystemResource(new File(inLinePath.getKey());
helper.addInline(inLinePath.getValue(), res);
}
}
mailSender.send(mimeMessage);
return new Result(true);
} catch (Exception e) {
e.printStackTrace();
log.error("邮件发送异常:"+e.getMessage(),e);
return new Result(1,"mail failed to send,"+e.getMessage());
}
}
签名中使用图片。内联资源的加载例子:
private void addInLineImages(MimeMessageHelper helper)
throws MessagingException {
ClassPathResource logoImage = new ClassPathResource(
"template/email/imgs/logo.png");
ClassPathResource barImage = new ClassPathResource(
"template/email/imgs/code.png");
helper.addInline("code", barImage, "image/x-png");
helper.addInline("logo", logoImage, "image/x-png"); // <img src="cid:logo"/>
}