1
zj
2025-04-17 ff2d1f5acdadc466d7e199028ef385ae8ca277e7
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package email.internal;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Map;
import java.util.Properties;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.sun.mail.util.MailSSLSocketFactory;
import email.EmailPropertiesUtil;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
 
import email.sender.EmailMessage;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import javax.net.ssl.*;
import java.security.cert.X509Certificate;
public class InternalEmailSenderServiceImpl implements InternalEmailSenderService, InitializingBean {
    private JavaMailSenderImpl mailSender;
    private static final Logger logger = LoggerFactory.getLogger(InternalEmailSenderServiceImpl.class);
    private SimpleMailMessage mailMessage;
    private FreeMarkerConfigurer freeMarkerConfigurer;
 
    @Override
    public void afterPropertiesSet() throws GeneralSecurityException {
        mailSender = new JavaMailSenderImpl();
        mailSender.setUsername(EmailPropertiesUtil.getProperty("email.username"));
        mailSender.setPassword(EmailPropertiesUtil.getProperty("email.password"));
        mailSender.setHost(EmailPropertiesUtil.getProperty("email.host"));
        Properties javaMailProperties = new Properties();
        javaMailProperties.setProperty("mail.smtp.port", "465");
        javaMailProperties.setProperty("mail.smtp.starttls.enable", "true");
        javaMailProperties.setProperty("mail.smtp.auth", "true");
        javaMailProperties.setProperty("mmail.debug", "true");
        javaMailProperties.setProperty("mail.smtp.host", "smtp.gmail.com");
        javaMailProperties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        javaMailProperties.setProperty("mail.smtp.socketFactory.port", "465");
        MailSSLSocketFactory sf = new MailSSLSocketFactory("TLSv1.2");
        sf.setTrustAllHosts(true);
        javaMailProperties.put("mail.smtp.ssl.socketFactory",sf);
        javaMailProperties.setProperty("mail.smtp.ssl.portocols","TLSv1.2");
        mailSender.setJavaMailProperties(javaMailProperties);
        mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(EmailPropertiesUtil.getProperty("email.from"));
        freeMarkerConfigurer = new FreeMarkerConfigurer();
        freeMarkerConfigurer.setTemplateLoaderPath("classpath:email/ftl");
        Properties settings = new Properties();
        settings.setProperty("template_update_delay", "1800");
        settings.setProperty("default_encoding", "UTF-8");
        settings.setProperty("locale", "zh_CN");
        freeMarkerConfigurer.setFreemarkerSettings(settings);
    }
 
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)  // 设置连接超时
            .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)     // 设置读取超时
            .writeTimeout(30, java.util.concurrent.TimeUnit.SECONDS)    // 设置写入超时
            .build();
 
    private static final String API_URL = "https://www.aoksend.com/index/api/send_email";
    private static final String APP_KEY = "d30ca7063ad44bd832bc934ff94a443b";  // 从环境变量或配置文件中获取
    @Override
    public void send(EmailMessage emailMessage) {
        // 验证邮件信息数据的有效性
        if (emailMessage == null || emailMessage.getTomail() == null || emailMessage.getContent() == null) {
            logger.error("无效的邮件信息数据。");
            return;
        }
 
        try {
            logger.info("----- 开始发送邮件 -----");
            logger.info("发送邮件到: " + emailMessage.getTomail() + ", 来自: " + emailMessage.getContent());
 
            // 使用 URL 构建器构建带有查询参数的 URL
            HttpUrl.Builder urlBuilder = HttpUrl.parse(API_URL).newBuilder();
            urlBuilder.addQueryParameter("app_key", APP_KEY);
            urlBuilder.addQueryParameter("template_id", "E_117228484621");
            urlBuilder.addQueryParameter("to", emailMessage.getTomail());
 
            // 将邮件内容以 JSON 形式传递
            String json = "{\"code\":\"" + emailMessage.getContent() + "\"}";
            urlBuilder.addQueryParameter("data", json);  // 确保正确编码
 
            // 构建请求体,使用 POST 方法
            RequestBody body = RequestBody.create(
                    json, MediaType.parse("application/json; charset=utf-8")
            );
 
            // 构建 POST 请求
            Request request = new Request.Builder()
                    .url(urlBuilder.build())
                    .post(body)  // 使用 POST 方法,并传递请求体
                    .addHeader("app_key", APP_KEY)
                    .build();
 
            // 执行请求
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    logger.error("邮件发送失败。HTTP 响应码: " + response.code());
                    return;
                }
 
                logger.info("----- 邮件发送成功 -----");
                // 可选:记录响应体的内容(如果需要)
                logger.debug("响应内容: " + response.body().string());
            }
 
        } catch (IOException e) {
            logger.error("邮件发送失败【IOException】", e);
        } catch (Exception e) {
            logger.error("邮件发送失败【Exception】", e);
        }
    }
 
    /**
     * 获取模板并将内容输出到模板
     * 
     * @param content
     * @return
     */
    private String getMailText(String ftlname, Map<String, Object> map) {
        String html = "";
 
        try {
 
            // 装载模板
            Template tpl = this.freeMarkerConfigurer.getConfiguration().getTemplate(ftlname);
            // 加入map到模板中 输出对应变量
            html = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
 
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return html;
    }
 
    public void setMailSender(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }
 
    public void setMailMessage(SimpleMailMessage mailMessage) {
        this.mailMessage = mailMessage;
    }
 
    public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
        this.freeMarkerConfigurer = freeMarkerConfigurer;
    }
 
}