【问题标题】:Unable to attach CSV to a SendGrid email无法将 CSV 附加到 SendGrid 电子邮件
【发布时间】: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


    【解决方案1】:

    您正在尝试添加为“base64”,但我们也可以添加如下所示的二进制数据

    with open('predictions_test.csv', 'rb') as fd:
        attachment = Attachment()
        attachment.content = fd.read()
        attachment.filename = "predictions_test.csv"
        attachment.disposition = "attachment"
        message.add_attachment(attachment)
        fd.close()
    

    【讨论】:

    猜你喜欢
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2014-07-16
    • 1970-01-01
    • 2016-11-30
    • 2020-06-27
    相关资源
    最近更新 更多