python - 如何在 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
解决方案
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
推荐阅读
- html - 如何在struts中验证值
- javascript - 使用钩子处理 React 中的文件上传状态
- jenkins - 如何将 Jenkins 构建参数传递给 JMETER 属性变量
- r - 如何在 R 中构建一个函数,将变量拆分为区间并计算区间的平均值、标准差和计数
- mysql - 在没有 CTE 的情况下删除 MySql 中的多行
- python - 如何中断线程定时器?
- amazon-web-services - Amazon SQS FIFO 队列 - 总共获得 10 条消息,但仍强制执行 MessageGroupId 计数?
- javascript - 使用jquery获取输入字段的值
- angular - 无法将节点模块添加到 Angular 项目
- python - 如何为 Sportmonks 获取 api_token?