python 为Sendgrid的电子邮件API编码CSV文件

c2e8gylq  于 2023-05-27  发布在  Python
关注(0)|答案(3)|浏览(154)

我正在尝试使用R/Python和Sendgrid的Email 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

厨房Flume教程
在我项目的最后一步之前都没有遇到任何问题。
任何帮助将不胜感激。值得注意的是,我的强项是R,但我通常可以在互联网的帮助下在python中将东西组合在一起。

mepcadol

mepcadol1#

在将b64data赋值给attachment.content之前,需要将其转换为常规字符串。Sendgrid构建了一个JSON负载,它在请求中发送,所以它不知道如何序列化分配给attachment.content的值,在本例中是bytestring

str(b64data,'utf-8')

参考资料:

  • https://github.com/sendgrid/sendgrid-python/blob/master/USAGE.md#post-mailsend
ni65a41a

ni65a41a2#

以下是如何将内存中的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')
z4iuyo4d

z4iuyo4d3#

import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition)

def send_email_with_attachment(api_key, sender_email, recipient_email, subject, html_content, attachment_path):
    message = Mail(
        from_email=sender_email,
        to_emails=recipient_email,
        subject=subject,
        html_content=html_content
    )

    with open(attachment_path, 'rb') as attachment_file:
        attachment_data = attachment_file.read()

    encoded_file = os.path.basename(attachment_path)
    attached_file = Attachment(
        FileContent(attachment_data),
        FileName(encoded_file),
        FileType('application/html'),
        Disposition('attachment')
    )

    message.attachment = attached_file

    try:
        sg = SendGridAPIClient(api_key=api_key)
        response = sg.send(message)
        print("Email sent successfully.")
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print("Error sending email.")
        print(str(e))

# Provide your SendGrid API key
api_key = 'YOUR_SENDGRID_API_KEY'

# Provide the sender and recipient email addresses
sender_email = 'sender@example.com'
recipient_email = 'recipient@example.com'

# Provide the email subject and HTML content
subject = 'Email with HTML attachment'
html_content = '<html><body><h1>Example HTML Email</h1><p>This is an example email with an HTML attachment.</p></body></html>'

# Provide the path to the HTML file you want to attach
attachment_path = 'path/to/attachment.html'

# Send the email
send_email_with_attachment(api_key, sender_email, recipient_email, subject, html_content, attachment_path)

    enter code here

相关问题