#
luxiaotao1123
2025-02-12 71eeac34fee9f5a53168e0872e5fb7b855c0b4c8
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
62
63
64
65
66
67
68
package com.vincent.rsf.server.common.service;
 
import com.alibaba.fastjson.JSON;
import com.vincent.rsf.common.utils.Utils;
import com.vincent.rsf.framework.common.Cools;
import com.vincent.rsf.server.system.enums.EmailType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
 
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;
 
@Slf4j
@Service
public class EmailService {
 
    @Value("${spring.mail.username}")
    private String from;
 
    private final static String TEMPLATE = "Your verification code is: ${code}";
 
    @Autowired
    @SuppressWarnings("all")
    private JavaMailSender mailSender;
 
    public boolean sendEmail(String to, EmailType emailType, Map<String, Object> param) {
 
        String subject = emailType.subject;
        String content = emailType.content;
        if (!Cools.isEmpty(param) && !param.isEmpty()) {
            content = Utils.processTemplate(content, param);
        }
 
        boolean sendRes = this.send(this.from, to, subject, content);
        if (sendRes) {
            log.info("Email sent successfully. To: {}, Subject: {}, Parameter: {}"
                    , to
                    , subject
                    , JSON.toJSONString(param));
        }
        return sendRes;
    }
 
    public boolean send(String from, String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            message.setFrom(from);
 
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content);
 
            mailSender.send(message);
            return true;
        } catch (MailException | MessagingException e) {
            log.error(this.getClass().getSimpleName(), e);
            return false;
        }
    }
 
}