我正在嘗試將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:錯誤的請求。
我的代碼有什麼問題?
你能不能檢查,如果該請求是使用VLID https://sendgrid.com/docs/課堂/發送/ v3_Mail_Send/sandbox_mode.html – WannaBeCoder
我認爲問題是圍繞base64線。如果我像這裏設置內容https://github.com/sendgrid/sendgrid-python/blob/ca96c8dcd66224e13b38ab8fd2d2b429dd07dd02/examples/helpers/mail/mail_example.py#L66它的工作原理。但是當我用base64編碼使用我的pdf文件時,我得到了錯誤 – John