LoginSignup
4
2

More than 3 years have passed since last update.

SendGridのWeb APIでメールを送る方法(python)

Last updated at Posted at 2021-01-26

全世界で利用されているメール配信サービスのSendGridを使って簡単にメールを送ります。

大まかな手順
- SendGridアカウント登録
- API Key発行
- SendGridライブラリのインストール
- プログラムの記述

SendGridアカウント登録

まずは、SendGridでアカウント登録してください。
少し質問項目が多いですが、用途に合わせて真面目に回答しましょう。
問題なければ1~2日でアカウント作成が完了します。(無料利用で大丈夫です)

API Key発行

アカウント作成後、API Keyを発行します。
SendGridの管理ページを開きます。

[Settings]->[API Keys]、[Create API Key]の順でボタンをクリックして設定画面を開きます。
スクリーンショット 2021-01-19 9.46.49.png

API Keyでのアクセス権限を設定します。
[API Key Name]を入力し、[API Key Permissions]は[Restricted Access]を選択します。

スクリーンショット 2021-01-19 9.53.48.png

[Access Details]は[Mail Send]>[Mail Send]を有効にします。(バーの右側にある丸い箇所をクリック)
スクリーンショット 2021-01-19 9.53.59.png

それだけ有効にしたら、[Create & View]で発行
スクリーンショット 2021-01-19 9.54.12.png

画面に表示されたAPI Keyをメモしてプログラムで読み込みます。

SendGridライブラリのインストール

sendgridライブラリのインストールはGitHub からダウンロードしてくるか、pip installコマンドでインストールします。

terminal
$ pip install sendgrid

プログラムの記述

公式ドキュメントをコピーして貼り付けます。

python3
# using SendGrid's Python Library
# https://github.com/sendgrid/sendgrid-python
import sendgrid

client = sendgrid.SendGridClient("SENDGRID_APIKEY")
message = sendgrid.Mail()

message.add_to("test@sendgrid.com")
message.set_from("you@youremail.com")
message.set_subject("Sending with SendGrid is Fun")
message.set_html("and easy to do anywhere, even with Python")

client.send(message)

以上です。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2