我想知道我是否可以通过smtplib发送一个matplotlib pyplot。我的意思是,在我绘制这个数据帧之后:
In [3]: dfa
Out[3]:
day imps clicks
70 2013-09-09 90739468 74609
69 2013-09-08 90945581 72529
68 2013-09-07 91861855 70869
In [6]: dfa.plot()
Out[6]: <matplotlib.axes.AxesSubplot at 0x3f24da0>我知道我可以用
plt.show()但是对象本身存储在哪里呢?或者我对matplotlib有什么误解?有没有办法在python中将其转换为图片或html,这样我就可以通过smtplib发送它?谢谢!
发布于 2013-09-12 21:53:44
可以使用figure.savefig()将打印保存到文件。下面是我将绘图输出到文件的示例:
fig = plt.figure()
ax = fig.add_subplot(111)
# Need to do this so we don't have to worry about how many lines we have -
# matplotlib doesn't like one x and multiple ys, so just repeat the x
lines = []
for y in ys:
lines.append(x)
lines.append(y)
ax.plot(*lines)
fig.savefig("filename.png")然后,只需将图像附加到您的电子邮件(如recipe in this answer)。
发布于 2014-02-19 02:37:44
还可以在内存中执行所有操作,将其保存到BytesIO缓冲区,然后将其提供给有效负载:
import io
from email.encoders import encode_base64
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
buf = io.BytesIO()
plt.savefig(buf, format = 'png')
buf.seek(0)
mail = MIMEMultipart()
...
part = MIMEBase('application', "octet-stream")
part.set_payload( buf.read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'anything.png')
mail.attach(part)发布于 2022-01-04 07:04:18
我不喜欢用SMTP和电子邮件库来做这件事,所以我决定自己解决这个问题,并创建了一个更好的发送电子邮件的库。您可以毫不费力地将Matplotlib图形作为附件包含在HTML正文中:
# Create a figure
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([1,2,3,2,3])
from redmail import EmailSender
# Configure the sender (pass user_name and password if needed)
email = EmailSender(host="<SMTP HOST>", port=0)
# Send an email
email.send(
subject="A plot",
sender="me@example.com",
receivers=["you@example.com"],
# A plot in body
html="""
<h1>A plot</h1>
{{ embedded_plot }}
""",
body_images={
"embedded_plot": fig
},
# Or plot as an attachment
attachments={
"attached_plot.png": fig
}
)这个库(希望)应该是你从电子邮件发送者所需要的一切。您可以从PyPI安装它:
pip install redmailhttps://stackoverflow.com/questions/18766060
复制相似问题