2016-11-17 126 views
3

我正在嘗試將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

回答

6

我找到了解決方案。我換成這一行:

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

1

這是我的解決方案,與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() 
相關問題