SendGrid模板使用方式一


特別提示:本人博客部分有參考網絡其他博客,但均是本人親手編寫過並驗證通過。如發現博客有錯誤,請及時提出以免誤導其他人,謝謝!歡迎轉載,但記得標明文章出處: http://www.cnblogs.com/mao2080/

1、問題描述

  使用SendGrid模板Java調用發送樣例。

2、操作方法

1、相關POM

       <dependency>
           <groupId>com.sendgrid</groupId>
           <artifactId>sendgrid-java</artifactId>
           <version>4.0.1</version>
       </dependency>
       <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
           <version>1.2.62</version>
       </dependency>

2、sendGrid配置模板

菜單路徑:Email API  -> Dynamic Templates  注意:變量使用{{}} 包起來

Hi {{name}}
You have canceled Subscription renewal. The subscription will still be available until {{date}}. Thanks for choosing our service!
Have questions? Contact US
{{phone}}

3、相關Code

package com.sendgrid;

import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class SendGridAPI {

    public static void main(String[] args) throws Exception {
		//模板ID
        String templateId = "d-xxxx";
		//發件人
        String from = "xxxx@qq.com";
		//收件人
        String to = "mao2080@sina.com";
		//參數
        Map<String, String> params = new HashMap<>();
        params.put("name", "Jack Chen");
        params.put("date", "2020-04-07");
        params.put("phone", "0755-8888xxx");

        try {
			//SendGrid 秘鑰
            String apiKey = "SG.YYY.XXX";
            SendGrid sg = new SendGrid(apiKey);
            Request request = new Request();
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(getEmailContent(from, to, templateId, params));
            Response response = sg.api(request);
            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (Exception ex) {
            throw ex;
        }
    }

    /**
     * 組織郵件內容模板
     * @param from 發件方
     * @param to 收件方
     * @param templateId 模板ID
     * @param params 參數
     * @return
     */
    private static String getEmailContent(String from, String to, String templateId, Map<String, String> params){
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("from", new Email(from));
        dataMap.put("template_id", templateId);
        Map<String, Object> persMap = new HashMap<>();
        persMap.put("to", Arrays.asList(new Email(to)));
        persMap.put("dynamic_template_data", params);
        dataMap.put("personalizations", Arrays.asList(persMap));
        return JSON.toJSONString(dataMap);
    }
}

3、其他方式

  https://www.cnblogs.com/mao2080/p/12655939.html

4、參考網站

  https://github.com/sendgrid/sendgrid-java/blob/master/USE_CASES.md


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM