如何发送电子邮件与dataframe作为附件使用sendgrid api在python?



嘿,我需要发送电子邮件通知每当一个事件发生,我能够发送电子邮件,但我不确定如何附加数据帧作为附件到它。

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

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

最新更新