概要

仕事でSendGridのAPIを使ってメール送信を行う機会があったのでそのメモ。

コード

基本的には下記のREADMEを見ればおおよそ分かる。

https://github.com/sendgrid/sendgrid-python

ライブラリをimportしてあげれば、メールの送信は下記だけで可能。

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

SENDGRID_API_KEY='XXXXX'

def sendMail(mailAddress, name):
    textData = htmlText.format(name=name)
    message = Mail(
        from_email = MAILFROM,
        to_emails = mailAddress,
        subject = '[TEST]テストメール',
        html_content = textData
        )
    try:
        sg = SendGridAPIClient(SENDGRID_API_KEY)
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e.message)

htmlText = """
{name}さん
こんにちは
これはテストメールです
"""

SendGridはWordPressのプラグインも用意されていたり、APIがとてもよく出来ているうえに各言語のライブラリも充実しているので、メールの送信だけならSendGridに任せるのをオススメします。

カテゴリー: Python