如何使用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

 


免責聲明!

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



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