我正在使用API发送所请求PDF的二进制文件。我想通过SendGrid将其作为附件发送电子邮件,但我一直遇到问题。
到目前为止,我已经尝试过:
我在Stackoverflow和SendGrid自己的Python Github上都找到了一些Q& A,但它似乎主要用于pdf文件,而不是二进制数据。大多数人似乎都说"将它编码为utf-8",但在这种情况下它最终会被破坏。关于我还能做什么的任何线索都能正确发送文件?
以下是执行Sendgrid的功能:
def to_sendgrid(my_email, other_email, text, attachment_data):
subject = "Sample pdf attached."
from_email = Email(my_email)
to_email = Email(other_email)
content = Content("text/plain", text)
mail = Mail(from_email, subject, to_email, content)
attachment_data = base64.b64encode(attachment_data.encode("utf-8"))
attachment = Attachment()
attachment.set_content(attachment_data)
attachment.set_type("application/pdf")
attachment.set_filename("sample.pdf")
attachment.set_disposition("attachment")
attachment.set_content_id("Sample")
mail.add_attachment(attachment)
try:
sendgrid_client.client.mail.send.post(request_body=mail.get())
except Exception as e:
print str(e)