Python Sendgrid发送带有PDF附件文件的电子邮件

时间:2016-11-17 13:19:35

标签: python pdf email-attachments sendgrid

我正在尝试将PDF文件附加到sendGrid发送的电子邮件中。

这是我的代码:

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

from_email = Email("from@example.com")
subject = "subject"
to_email = Email("to@example.com")
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 Error 400:Bad Request。

我的代码出了什么问题?

4 个答案:

答案 0 :(得分:13)

我找到了解决方案。我替换了这一行:

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

由此:

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

encoded = base64.b64encode(data)

现在它有效。我可以在set_content:

中发送编码文件
attachment.set_content(encoded)

注意:以上答案适用于Sendgrid v2或更低版本。对于v3及以上使用:

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

答案 1 :(得分:9)

这是我的解决方案,与Sendgrid V3一起使用

    # 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("origin@gmail.com")
    to_email = Email('recipient@gmail.com')
    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()

答案 2 :(得分:1)

直接从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='from_email@example.com',
    to_emails='to@example.com',
    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)

答案 3 :(得分:1)

<块引用>

“如何将多个文件附加到一封邮件中?”

构建附加附件:

file_path = 'test_filename1.pdf'
with open(file_path, 'rb') as f:
    data = f.read()
    f.close()
encoded = base64.b64encode(data).decode()
attachment1 = Attachment()
attachment1.file_content = FileContent(encoded)
attachment1.file_type = FileType('application/pdf')
attachment1.file_name = FileName('test_filename1.pdf')
attachment1.disposition = Disposition('attachment')
attachment1.content_id = ContentId('Example Content ID1')

file_path = 'test_filename2.pdf'
with open(file_path, 'rb') as f:
    data = f.read()
    f.close()
encoded = base64.b64encode(data).decode()
attachment2 = Attachment()
attachment2.file_content = FileContent(encoded)
attachment2.file_type = FileType('application/pdf')
attachment2.file_name = FileName('test_filename2.pdf')
attachment2.disposition = Disposition('attachment')
attachment2.content_id = ContentId('Example Content ID2')

mail.attachment = [attachment1,attachment2]