web-dev-qa-db-ja.com

Python SendgridはPDF添付ファイル付きのメールを送信します

Sendgridで送信されたメールにPDFファイルを添付しようとしています。

これが私のコードです:

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))

from_email = Email("[email protected]")
subject = "subject"
to_email = Email("[email protected]")
content = Content("text/html", email_body)

pdf = open(pdf_path, "rb").read().encode("base64")
attachment = Attachment()
attachment.set_content(pdf)
attachment.set_type("application/pdf")
attachment.set_filename("test.pdf")
attachment.set_disposition("attachment")
attachment.set_content_id(number)

mail = Mail(from_email, subject, to_email, content)
mail.add_attachment(attachment)

response = sg.client.mail.send.post(request_body=mail.get())

print(response.status_code)
print(response.body)
print(response.headers)

しかし、Sendgrid PythonライブラリはエラーHTTPエラー400:不正なリクエストをスローしています。

私のコードの何が問題になっていますか?

9
John

私は解決策を見つけました。私はこの行を置き換えました:

pdf = open(pdf_path, "rb").read().encode("base64")

これで :

with open(pdf_path, 'rb') as f:
    data = f.read()

encoded = base64.b64encode(data)

今では動作します。 set_contentでエンコードされたファイルを送信できます:

attachment.set_content(encoded)

注:上記の回答はSendgridv2以下で機能します。 v3以降で使用する場合:

encoded = base64.b64encode(data).decode()
14
John

これが私のソリューションです。SendgridV3で動作します

    # Where it was uploaded Path.
    file_path = "MY_FILE_PATH"

    with open(file_path, 'rb') as f:
        data = f.read()

    # Encode contents of file as Base 64
    encoded = base64.b64encode(data).decode()

    """Build attachment"""
    attachment = Attachment()
    attachment.content = encoded
    attachment.type = "application/pdf"
    attachment.filename = "my_pdf_attachment.pdf"
    attachment.disposition = "attachment"
    attachment.content_id = "PDF Document file"

    sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)

    from_email = Email("[email protected]")
    to_email = Email('[email protected]')
    content = Content("text/html", html_content)

    mail = Mail(from_email, 'Attachment mail PDF', to_email, content)
    mail.add_attachment(attachment)

    try:
        response = sg.client.mail.send.post(request_body=mail.get())
    except urllib.HTTPError as e:
        print(e.read())
        exit()
10
Eddwin Paz

Sendgrid docs から直接:

import urllib.request as urllib
import base64
import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition, ContentId)

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

message = Mail(
    from_email='[email protected]',
    to_emails='[email protected]',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')
file_path = 'example.pdf'
with open(file_path, 'rb') as f:
    data = f.read()
    f.close()
encoded = base64.b64encode(data).decode()
attachment = Attachment()
attachment.file_content = FileContent(encoded)
attachment.file_type = FileType('application/pdf')
attachment.file_name = FileName('test_filename.pdf')
attachment.disposition = Disposition('attachment')
attachment.content_id = ContentId('Example Content ID')
message.attachment = attachment
try:
    sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sendgrid_client.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)
0
John R Perry