LoginSignup
0
0

More than 3 years have passed since last update.

【Python+SendGrid】ZIPファイルを添付

Posted at

はじめに

Python+SendGridで送信するメールに、zipファイルを添付したくて実装してみました。

環境

  • Python 3.6.5
  • SendGrid api v3

コード

import部分

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

送信部分

一部抜粋

    # create mail object
    with pathlib.Path(Utils.getAbsolutePath("./mail_body.txt")).open(mode="r", encoding="UTF-8") as f:
        mail = Mail(from_email=mail_from, to_emails=mail_to,
                    subject=subject, plain_text_content=f.read())
    # attachment zip file
    with pathlib.Path(Utils.getAbsolutePath("./" + zip_name)).open(mode="rb") as zf:
        encoded = base64.b64encode(zf.read()).decode("UTF-8")
        attachment = Attachment(
            file_content=encoded, file_name=zip_name, file_type="application/zip")
        mail.add_attachment(attachment)
    # send mail start
    sg = SendGridAPIClient(api_key=self.__mail_config.apikey)
    response = sg.send(mail)

以上

0
0
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
0
0