forked from kidgrow-microservices-platform

dougang
2020-11-04 b5c197d06d35d56a9fbcb379e49ad07698d7dd90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.kidgrow.email.controller;
 
import com.kidgrow.common.base.ResponseCode;
import com.kidgrow.common.model.ResultBody;
import com.kidgrow.email.model.MailModel;
import com.kidgrow.email.service.MailSendService;
import com.kidgrow.email.service.MailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
 
import java.util.Map;
 
/**
 * 石家庄喜高科技有限责任公司 版权所有 © Copyright 2020<br>
 *
 * @Description: 邮件发送<br>
 * @Project: <br>
 * @CreateDate: Created in 2020/2/17 11:44 <br>
 * @Author: <a href="4345453@kidgrow.com">liuke</a>
 */
@RestController
public class SendMailController implements MailSendService {
 
    @Autowired
    private MailService mailService;
 
    @Autowired
    private TemplateEngine templateEngine;
 
    /**
     * 发送邮件
     *
     * @param mailModel
     * @return BaseResponse
     */
    @Override
    public ResultBody sendTemplateMail(@RequestBody MailModel mailModel) {
        //创建邮件正文
        if (StringUtils.isBlank(mailModel.getSubject()) || mailModel.getToMailAddrs() == null || mailModel.getToMailAddrs().size() == 0) {
            ResultBody.failed(ResponseCode.ERROR_PARAMS, "收件人或邮件主题不能为空!");
        }
        Context context = new Context();
        if (mailModel.getMsg() != null) {
            for (Map.Entry<String, Object> m : mailModel.getMsg().entrySet()) {
                context.setVariable(m.getKey(), m.getValue());
            }
        }
        try {
            String emailContent = templateEngine.process(mailModel.getTemplate(), context);
            mailService.sendHtmlMail(mailModel.getToMailAddrs(), mailModel.getSubject(), emailContent, mailModel.getFiles());
            return ResultBody.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.failed(e.getMessage());
        }
    }
}