通过Mai发送创建的绘图

2024-10-01 07:39:09 发布

您现在位置: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,熊猫和matplotlib.pyplot文件你知道吗

所以现在我想知道我是怎么通过电子邮件把这个情节发给别人的。 我想用相同的代码来做,不想保存图形。你知道吗


Tags: columns数据数据库dataframedfexecutesqlcount
1条回答
网友
1楼 · 发布于 2024-10-01 07:39:09

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

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

注意:我还没有测试这些,但他们应该不会太远的工作。你知道吗

相关问题 更多 >