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
个性签名:1.01的365次方=37.78343433289 >>>1
0.99的365次方= 0.02551796445229 <<<1
每天进步一点点的目标,贵在坚持…

浙公网安备 33010602011771号