python - 通过邮件发送创建的绘图
问题描述
我使用 MySQLdb 建立与我的 SQL 数据库的连接。然后我用
Cursor = connection.cursor()
anz = Cursor.execute(myquery)
然后我用它做了一个数据框
df = DataFrame(anz, columns = ['likeval','count'])
然后我画了
df.plot(kind='hist', x='Anzahl', y='count')
我导入了 MySQLdb、pandas 和 matplotlib.pyplot
所以现在我想知道如何通过电子邮件将这个情节发送给某人。我想用相同的代码来做,不想保存图表。
解决方案
首先,您需要将图形保存到虚拟文件对象:
import io
img_format = 'png'
df.plot(...)
f = io.BytesIO()
plt.savefig(f, format=img_format)
f.seek(0)
现在,f
包含图像数据,可以read
像文件一样来自:
img_data = f.read()
接下来,让我们创建电子邮件:
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
# Add From/To/Subject fields by using msg like a dictionary
通过电子邮件发送图像有两种选择:
- Base64 编码并将其传递到 HTML
<img>
标记内 - 将其添加为附件
选项1:
from base64 import b64encode
msg.add_header('Content-Type','text/html')
msg.set_content(f'''<html>
<head></head>
<body>
<img src="data:image/{img_format};base64, {b64encode(img_data).decode('ascii')}">
</body>
</html>''')
选项 2:
msg.add_attachment(img_data, maintype='image', subtype=img_format)
最后,发送电子邮件:
import smtplib
s = smtplib.SMTP('localhost')
s.starttls()
s.login(...)
s.sendmail(msg['From'], [msg['To']], msg.as_string())
s.quit()
注意:我没有测试过这些,但它们应该离工作不远。
推荐阅读
- javascript - 如何将 Env Vars 传递给 Gatsby 中的 Sass 插件?
- terraform - RDS 的 Terraform AWS 安全组条目
- html - CSS 背景图像无法正常工作
- sql - 如何在 SQL Server 中检查调用存储过程
- delphi - Delphi StringGrid 以不需要的列间距显示
- mysql - MariaDB最新10.5版本无法更改root密码,没有skip-grant-tables无法使用
- python - 如何使用碰撞矩形或其他东西从鼠标坐标中获取对象(或它在 NumPy 数组中的索引)?(Pygame 2D)
- php - 如何在 php 中读取 html 元素的类名?
- react-native - 如何正确调用此自定义钩子,并避免无限重新渲染?
- python - 如何在深度图上进行彩色图像分割并创建一个代表结果的 9 个索引数组?