【问题标题】:Encode CSV file for Sendgrid's Email API为 Sendgrid 的电子邮件 API 编码 CSV 文件
【发布时间】:2017-12-09 13:41:09
【问题描述】:

我正在尝试使用 R/Python 和 Sendgrid 的电子邮件 API 构建客户端报告引擎。我可以发送电子邮件,但我需要做的最后一件事是附上客户的 CSV 报告。

我尝试了多种方法,包括对文件进行 base64 编码以及将字符串从 R 写入磁盘到 python,但没有运气。也就是说,我似乎陷入了这个错误:

TypeError: 'bytes' 类型的对象不是 JSON 可序列化的

我的代码是:

with open('raw/test-report.csv', 'rb') as fd:
     b64data = base64.b64encode(fd.read())
attachment = Attachment()
attachment.content = b64data
attachment.filename = "your-lead-report.csv"
mail.add_attachment(attachment)

令人困惑的是,如果我只是将b64data 替换为该行

attachment.content = 'TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12'

一封带有附件的电子邮件。

供参考,我一直在使用:

https://github.com/sendgrid/sendgrid-python

kitchen sink tutorial

在我的项目的最后一步之前没有任何问题。

任何帮助将不胜感激。值得注意的是,我的强项在R,但我通常可以借助互联网在python 中一起破解。

【问题讨论】:

    标签: python email sendgrid


    【解决方案1】:

    您需要先将b64data 转换为常规字符串,然后再将其分配给attachment.content。 Sendgrid 构建了一个 JSON 有效负载,它在请求中发送,因此它不知道如何序列化分配给 attachment.content 的值,在本例中为 bytestring

    str(b64data,'utf-8')
    

    参考资料:

    【讨论】:

    • 成功了,谢谢!我玩过这个的变种,但没有正确的顺序。非常感谢。
    【解决方案2】:

    以下是将内存中的 CSV 附加到 sendgrid 电子邮件的方法:

    import base64
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import (
        Mail, Attachment, FileContent, FileName,
        FileType, Disposition)
    from io import BytesIO
    import pandas as pd
    
    def send_email_with_csv(from_address, to_address, subject, content, dataframe, filename, filetype):
        message = Mail(
            from_email=from_address,
            to_emails=to_address,
            subject=subject,
            html_content=content)
        
        #%% Create buffered csv
        buffer = BytesIO()
        dataframe.to_csv(buffer);
        buffer.seek(0)
        data = buffer.read()
        encoded = base64.b64encode(data).decode()
        
        #%%
        attachment = Attachment()
        attachment.file_content = FileContent(encoded)
        attachment.file_type = FileType(filetype)
        attachment.file_name = FileName(filename)
        attachment.disposition = Disposition('attachment')
        message.attachment = attachment
        try:
            sendgrid_client = SendGridAPIClient('API_KEY')
            response = sendgrid_client.send(message)
            print(response.status_code)
            print(response.body)
            print(response.headers)
        except Exception as e:
            print(e.message)
    
    
    df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})
    
    send_email_with_csv(from_address='sender@sender.com',
                        to_address='example@recipient.com',
                        subject='Sending with Twilio SendGrid is Fun',
                        content='<strong>and easy to do anywhere, even with Python</strong>',
                        dataframe=df,
                        filename='spreadsheet.csv',
                        filetype='text/csv')
    

    【讨论】:

      猜你喜欢
      • 2016-11-30
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      相关资源
      最近更新 更多