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

问题描述:

我正在尝试将PDF文件附加到与sendgrid一起发送的电子邮件中。Python 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:错误的请求。

我的代码有什么问题?

+0

你能不能检查,如果该请求是使用VLID https://sendgrid.com/docs/课堂/发送/ v3_Mail_Send/sandbox_mode.html – WannaBeCoder

+0

我认为问题是围绕base64线。如果我像这里设置内容https://github.com/sendgrid/sendgrid-python/blob/ca96c8dcd66224e13b38ab8fd2d2b429dd07dd02/examples/helpers/mail/mail_example.py#L66它的工作原理。但是当我用base64编码使用我的pdf文件时,我得到了错误 – John

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

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) 
+1

就像一个侧面说明。你不需要'f.close()',因为退出'with'语句时文件关闭了。 – elgehelge

这是我的解决方案,与Sendgrid V3工作

with open(file_path, 'rb') as f: 
     data = f.read() 
     f.close() 
    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()