如何使用SendGrid发送邮件

特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/mao2080/

1、问题描述

  有客户要求使用SendGrid进行邮件发送,首先科普下:Sendgrid(https://sendgrid.com/),云邮件管理公司,是一个帮助企业用户管理、发送电子邮件的平台,该平台能够为用户电子邮件服务提供了安全可靠、可扩展的基础架构。SendGrid帮助企业用户处理邮件订阅、管理和反馈等事宜。同时SendGrid为用户提供分析服务,为用户提供关于电子邮件的跟踪请求、响应、垃圾邮件报告、无效电子邮件反馈、点击统计以及退订等诸多管理服务。

2、Java使用方法

  1、引用pom

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

  2、Java代码

package com.sendgrid;
import java.io.IOException;
public class Example {
    public static void main(String[] args) throws IOException {
        Email from = new Email("发件方@outlook.com");
        String subject = "Sending with Twilio SendGrid is Fun";
        Email to = new Email("收件方@gmail.com");
        Content content = new Content("text/plain", "and easy to do anywhere, even with Java");
        Mail mail = new Mail(from, subject, to, content);
        String apiKey = "xxx";//这个key来源参考4如何获取apiKey
        SendGrid sg = new SendGrid(apiKey);
        Request request = new Request();
        try {
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(mail.build());
            Response response = sg.api(request);
            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (IOException ex) {
            throw ex;
        }
    }
}

3、使用curl命令

1、参考链接:https://sendgrid.com/docs/for-developers/sending-email/api-getting-started/

2、需要将红色的代码替换为apiKey(这个key来源参考4如何获取apiKey)

curl --request POST 
--url https://api.sendgrid.com/v3/mail/send 
--header 'authorization: Bearer <<YOUR_API_KEY>>' 
--header 'content-type: application/json' 
--data '{"personalizations":[{"to":[{"email":"john.doe@example.com","name":"John Doe"}],"subject":"Hello, World!"}],"content": [{"type": "text/plain", "value": "Heya!"}],"from":{"email":"sam.smith@example.com","name":"Sam Smith"},"reply_to":{"email":"sam.smith@example.com","name":"Sam Smith"}}'

4、如何获取apiKey

原文地址:https://www.cnblogs.com/mao2080/p/11993313.html