首页 > 解决方案 > 如何在 python 中使用 sendgrid api 发送带有数据框作为附件的电子邮件?

问题描述

嘿,每当事件发生时,我都需要发送电子邮件通知,我可以发送电子邮件,但我不确定如何将数据框作为附件附加到它。

def send_mail(content):

    # Defining Email Body and Notificaion type.    
    html_content='Hi Team,</br><strong>{}</br></br>Thanks</strong></br></br>'.format(content)

    # Defining Email_Format.
    message = Mail(
        from_email='XXXXXX@.com',
        to_emails=['XXXXXX@.com'],
        subject='test',
        html_content=html_content)
    
    try:
        sg = SendGridAPIClient(SENDGRID_API_KEY)
        response = sg.send(message)
    except Exception as e:
        logging.error(e.message)
    
    return None

我可以通过上面的代码发送通知,但我需要将数据框作为附件附加到该邮件,我不知道如何附加它。

df_to_attach。--- 我需要将此数据框作为附件附加

Id   Name
1    rick
2    John
3    uran
4    Turan

标签: pythonpandassendgridsendgrid-api-v3

解决方案


Twilio SendGrid 开发人员布道者在这里。

正如 Joshua 在评论中建议的那样,将您的数据框转换为 CSV 格式,然后作为 CSV 文件附加。像这样的东西:

from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition, ContentId)
import base64

def send_mail(content, dataframe):

    # Defining Email Body and Notificaion type.    
    html_content='Hi Team,</br><strong>{}</br></br>Thanks</strong></br></br>'.format(content)

    # Defining Email_Format.
    message = Mail(
        from_email='XXXXXX@.com',
        to_emails=['XXXXXX@.com'],
        subject='test',
        html_content=html_content)
  
    base64_csv = base64.b64encode(dataframe.to_csv(index=False).encode())
    message.attachment = Attachment(FileContent(base64_csv),
                                    FileName('dataframe.csv'),
                                    FileType('text/csv'),
                                    Disposition('attachment'),
                                    ContentId('datafrane'))
    
    try:
        sg = SendGridAPIClient(SENDGRID_API_KEY)
        response = sg.send(message)
    except Exception as e:
        logging.error(e.message)
    
    return None

推荐阅读