SendGridのAPIは、Pythonで使えるものがGitHubで公開されていて、便利に使える。まぁだいたいのことはGitHubのページを見るのが一番良いのだが、自分でさっと使う用に、メモ書きしておく。
環境
環境は以下。
- Python 3.7.3
- sendgrid-python 6.0.5
GitHubのページは「GitHub – sendgrid/sendgrid-python: The Official Twilio SendGrid Led, Community Driven Python API Library」。基本的にはここを読むのが一番良い。特に「sendgrid-python/use_cases at master · sendgrid/sendgrid-python · GitHub」はありがたくて、添付ファイルの付け方とか「sendgrid-python/attachment.md at master · sendgrid/sendgrid-python · GitHub」を見ればよい話ではある。
サンプルコード
サンプルコードは以下。
import base64
import mimetypes
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (
Mail, Attachment, FileContent, FileName,
FileType, Disposition, ContentId)
SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
def convert_attachment(attachment_file):
"""添付ファイルをAttachmentにする"""
file_path = attachment_file
file_type = mimetypes.guess_type(file_path)[0]
with open(file_path, 'rb') as content:
data = content.read()
encoded = base64.b64encode(data).decode()
attachment = Attachment()
attachment.file_content = FileContent(encoded)
attachment.file_type = FileType(file_type)
attachment.file_name = FileName(os.path.basename(file_path))
attachment.disposition = Disposition('attachment')
attachment.content_id = ContentId('Sample')
return attachment
message = Mail(
from_email=senderのアドレス,
to_emails=送り先のアドレス,
subject="Attachment Test",
plain_text_content="test",
)
message.attachment = convert_attachment(添付ファイル)
sg_client = SendGridAPIClient(SENDGRID_API_KEY)
response = sg_client.send(message)
添付ファイルをAttachmentオブジェクトにする。sendgrid-python、Version 6になって使いやすくなった。
関連記事
Python の記事
- [2023年4月29日] Python3: Ctrl-cで割り込み処理
- [2023年3月27日] Pythonで深いネストのlistやDictの値を調べてDecimalがあればint or floatに変換する
- [2023年3月21日] motoでDynamoDBのMockを作成する
- [2021年11月18日] GKE + Flask で REST API
- ---本記事---
- [2019年4月4日] C1801: Do not use len(SEQUENCE) to determine if a sequence is empty (len-as-condition)と怒られた時
- [2019年4月3日] Python + SendGrid API でメールを送信する
- [2018年8月21日] boto3でS3にアップロードした画像が、ブラウザで表示するとダウンロードされてしまう時
- [2018年7月27日] Pandasで2列を比較してTrue/Falseの新たな列を作る。さらに1/0へのマッピング
- [2018年7月20日] pythonのpipで入れているもの
- [2018年6月25日] cronのpythonスクリプト内にあるjson.dump()でensure_ascii=Falseにして日本語出力しようとしてハマった
スポンサーリンク