なぜSendGridを使うのか
heroku上のアプリからでも、手軽にメールを送信できるから!
当初は、GmailAPIを使って自分のメルアドからメール送信するつもりだった...
しかし、そのためには、heroku上にGmailAPIのcredentialやらtokenをアップしなければならないということに気づく。
それらの情報を環境変数に入れてもいいが…GmailAPIのモジュールと環境変数の相性が悪そうだったので、herokuからでも手軽にメール送信ができそうなSendGridに逃げてきたのである...
この記事の対象者
- python3を使っている
- SendGrid(V3)で、テキストだけのメールは既に送信できる
- でも、画像を添付したメールを送信することができない
以上3つの条件を満たす方のみどうぞ
SendGridで画像付きメールを送信する方法を日本語で解説してるサイトを見つけられなかったので、記事に書くことにしました
や、外国語の記事も見つけられなかったけど
pythonでのSendGridの使い方
コチラの記事を参考にさせていただきました
https://qiita.com/Dalice/items/cb51687aae4dba3b2b1e
説明は省略させていただきます
テキストメール送る方法は他の記事を参考にして下さい(手抜きさせていただきます!)
ソースコード
テキストのみ送信の場合
import sendgrid
import sendgrid.helpers.mail as sg_helper
sg = sendgrid.SendGridAPIClient(apikey='sendgridのapikey')
message = sg_helper.Mail(
from_email=sg_helper.Email('hoge@email.com'),
subject='件名だよ',
to_email=sg_helper.Email('hogehoge@email.com'),
content=sg_helper.Content("text/html", '<h1>テストだよ<h1>')
)
response = sg.client.mail.send.post(request_body=message.get())
print(response.status_code)
print(response.body)
print(response.headers)
画像を送信する場合(本命)
import base64
import sendgrid
import sendgrid.helpers.mail as sg_helper
# このメソッドを追加しました
def prepare_image():
image_filepath = 'images/sample.png'
with open(image_filepath, 'rb') as f:
encoded = base64.b64encode(f.read()).decode()
attachment = sg_helper.Attachment()
attachment.content = encoded
attachment.type = 'image/png'
attachment.filename = 'filename.png'
attachment.disposition = 'attachment'
# attachment.set_content_id = 1 # なんかcomment outしてても動くし...
return attachment
sg = sendgrid.SendGridAPIClient(apikey='sendgridのapikey')
message = sg_helper.Mail(
from_email=sg_helper.Email('hoge@email.com'),
subject='件名だよ',
to_email=sg_helper.Email('hogehoge@email.com'),
content=sg_helper.Content("text/html", '<h1>テストだよ<h1>')
)
# これでattachment(画像)を添付できる
message.add_attachment(prepare_image())
response = sg.client.mail.send.post(request_body=message.get())
print(response.status_code)
print(response.body)
print(response.headers)
たったこれだけ、でも数時間かかったのだ...
ぜひぜひ皆様も参考にして下さい
SendGridでの画像添付の参考になったサイト
みなさんお馴染みのstackoverflow☆きらりん
https://stackoverflow.com/questions/40656019/python-sendgrid-send-email-with-pdf-attachment-file
この人はpdf送ろうとしてるよ