将 CSV 附加到 Python 中没有 CSV 的电子邮件

Attach CSV to email in Python without the CSV

我看过很多关于通过 Python 将 CSV 作为电子邮件附件发送的解决方案。

就我而言,我的 Python 代码需要从 Snowflake 视图中提取数据并将其作为 CSV 附件发送给用户组。虽然我知道如何使用 Pandas 数据帧中的 to_csv 来做到这一点,但我的问题是:我是否必须在外部创建 CSV 文件?我可以通过 MIMEText 简单地 运行 Pandas DF 吗?如果是这样,我在 header?

中使用什么文件名

您不必在磁盘上创建临时 CSV 文件,但您也不能只“附加数据框”,因为它没有指定的在线格式。使用 BytesIO 让 Pandas 将 CSV 序列化到内存:

df = pd.DataFrame(...)
bio = io.BytesIO()
df.to_csv(bio, mode="wb", ...)
bio.seek(0)  # rewind the in-memory file

# use the file object wherever a file object is supported
# or extract the binary data with `bio.getvalue()`