【发布时间】:2019-08-27 15:52:35
【问题描述】:
无法将 CSV 附加到通过 SendGrid API 发送的电子邮件。
我已经尝试了将内容参数作为 base64 编码的常规字符串传递的每次迭代,但我仍然收到相同的错误消息。
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Content, Email, Attachment
import numpy as np
import base64
fake_data = np.random.randint(5000, size=(82, 2))
np.savetxt('predictions_test.csv', fake_data, delimiter=",")
message = Mail(
from_email='FROM_EMAIL',
to_emails='TO_EMAIL',
subject='Sending with Twilio SendGrid is Fun',
html_content='<strong>Test Email Body</strong>')
with open('predictions_test.csv', 'rb') as fd:
b64data = base64.b64encode(fd.read())
fd.close()
attachment = Attachment()
attachment.content = str(b64data,'utf-8')
attachment.filename = "predictions_test.csv"
attachment.disposition = "attachment"
message.add_attachment(attachment)
try:
sg = SendGridAPIClient('APIKEY')
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(str(e.body))
Returns the following Error messages is the following:
b'{"errors":[{"message":"The attachment content is required.","field":"attachments.0.content","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.attachments.content"},{"message":"The attachment filename parameter is required.","field":"attachments.0.filename","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.attachments.filename"}]}'
【问题讨论】:
标签: python python-3.x csv sendgrid