shichongfu
2023-04-25 ce0b49552668d3331055e2b1a1447a743dc54939
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
package com.product.admin.util.email;
 
import java.io.IOException;
 
import com.product.admin.config.CmnConst;
import org.springframework.beans.factory.annotation.Value;
 
import com.product.core.entity.FieldSetEntity;
import com.product.core.exception.BaseException;
import com.sendgrid.Content;
import com.sendgrid.Email;
import com.sendgrid.Mail;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
 
public class SendGridSendEmail {
    
    @Value("${sendGrid.mail.user}")
    private static String sendGridUser;
 
    @Value("${sendGrid.mail.key}")
    private static String sendGridKey;
 
    /**
     * SendGrid发送邮件
     * @param addressInfo    收件人信息
     * @throws BaseException 
     */
    public static void sendMail(FieldSetEntity fseMailInfo) throws BaseException {
        
        
        //发件人,即配置的发件人邮箱地址
        Email from = new Email(sendGridUser);
        //收件人邮件地址
        Email to = new Email(fseMailInfo.getString("addressee"));
        //邮件主题
        String subject =fseMailInfo.getString("mail_title");
        //邮件内容
        Content content=null;
        if(fseMailInfo.getString(CmnConst.MAIN_CONTENT).indexOf("</html>")>-1) {
            content = new Content("text/html", fseMailInfo.getString(CmnConst.MAIN_CONTENT));
        }else {
            content = new Content("text/plain", fseMailInfo.getString(CmnConst.MAIN_CONTENT));
        }
        Mail mail = new Mail(from, subject, to, content);
        try {
            String apiKey = sendGridKey;
            SendGrid sg = new SendGrid(apiKey);
            Request request = new Request();
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(mail.build());
            Response response = sg.api(request);
            int statCode=response.getStatusCode();
            if(statCode<200 || statCode>=300) {    //发送失败!
                fseMailInfo.setValue(CmnConst.SEND_STAT, 2);
            }else {    //发送成功
                fseMailInfo.setValue(CmnConst.SEND_STAT, 1);
            }
        } catch (IOException ex) {
            fseMailInfo.setValue(CmnConst.SEND_STAT, 2);
            fseMailInfo.setValue("failure_reason", ex.getStackTrace());
        }
        fseMailInfo.setValue("smtp_username", sendGridUser);
        fseMailInfo.setValue("smtp_license_code", sendGridKey);
    }
}