首页 > 解决方案 > 通过邮件发送创建的绘图

问题描述

我使用 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

所以现在我想知道如何通过电子邮件将这个情节发送给某人。我想用相同的代码来做,不想保存图表。

标签: pythonpandasemailmatplotlib

解决方案


首先,您需要将图形保存到虚拟文件对象:

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

通过电子邮件发送图像有两种选择:

  1. Base64 编码并将其传递到 HTML<img>标记内
  2. 将其添加为附件

选项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()

注意:我没有测试过这些,但它们应该离工作不远。


推荐阅读