Matplotlib到smtplib

k75qkfdt  于 2023-05-01  发布在  其他
关注(0)|答案(3)|浏览(107)

我想知道我是否可以通过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发送?

odopli94

odopli941#

也可以在内存中执行所有操作,将其保存到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)
wmomyfyw

wmomyfyw2#

可以使用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)。

ruarlubt

ruarlubt3#

我不喜欢用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 redmail

文件:https://red-mail.readthedocs.io/en/latest/
源代码:https://github.com/Miksus/red-mail

相关问题