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になって使いやすくなった。
コメント