SendGridでメール送信

SendGridでメールを送ってみる。

環境

SendGrid APIキーの作成

API keyを作成します。公式のマニュアルはこちら。

API Keys

付与する権限を選択できるので、メール送信用の権限のみ付与します。

f:id:goodbyegangster:20191226103409p:plain

APIキーのテストをできるコマンドを用意してくれているので、それで動作を確認できます。下記コマンドから、 YOUR_API_KEY_HERE の部分に作成したAPIキーを登録して実行。

$ curl -i --request POST \
--url https://api.sendgrid.com/v3/mail/send \
--header 'Authorization: Bearer YOUR_API_KEY_HERE' \
--header 'Content-Type: application/json' \
--data '{"personalizations": [{"to": [{"email": "recipient@example.com"}]}],"from": {"email": "sender@example.com"},"subject": "Hello, World!","content": [{"type": "text/plain", "value": "Howdy!"}]}'
HTTP/1.1 202 Accepted
Server: nginx
Date: Wed, 25 Dec 2019 22:28:58 GMT
Content-Length: 0
Connection: keep-alive
X-Message-Id: JXi0ahVuSWSDMt_kY3EwFA
Access-Control-Allow-Origin: https://sendgrid.api-docs.io
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
Access-Control-Max-Age: 600
X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html

HTTPのステータス202が返ってくることを確認します。

メール送信

メール送信の方法として、Web APIを利用する方法とSMTPを利用する方法が用意されています。

f:id:goodbyegangster:20191226103428p:plain

Web APIとSMTPの違い

今回はAPIを利用します。

SDKのインストール

各言語向けのSDKが用意されているので、Python向けのものをインストールします。

$ pip install sendgrid

GitHub - sendgrid-python

送信

GitHubにあるQuickStartに、かなり丁寧に記載してくれているので、それを参考に実行。いろんな処理のサンプルコードを書いてくれています。

Quick Start

APIキーをインプット用のコンフィグファイルを作成。

config.ini

[DEFAULT]
API_KEY = (API Key)

サンプルのコードを参考に処理。

import os
import configparser
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

config = configparser.ConfigParser()
config.read('./config.ini', encoding='utf-8')
API_KEY = config['DEFAULT']['API_KEY']

message = Mail(
  from_email='from@example.com',
  to_emails='xxxxxxx@outlook.jp',
  subject='test mail',
  html_content='test message'
)

try:
  sg = SendGridAPIClient(api_key=API_KEY)
  response = sg.send(message)
  print(response.status_code)
  print(response.body)
  print(response.headers)
except Exception as e:
  print(str(e))