質問

I'm wondering if I can send out a matplotlib pyplot through smtplib. What I mean is, after I plot this dataframe:

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>

I know I can see the plot using

plt.show()

but where is the object itself stored? Or am I misunderstanding something about matplotlib? Is there a way to convert it to a picture or html within python so I can send it through smtplib? Thanks!

役に立ちましたか?

解決 2

You can use figure.savefig() to save your plot to a file. An example where I output a plot to a file:

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

Then just attach the image to your email (like the recipe in this answer).

他のヒント

It is also possible to do everything in memory saving to a BytesIO buffer and then feeding the payload with it:

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)

I did not like how messy it is to do this thing with SMTP and email libs so I decided to solve this on my own and created a nicer library for sending emails. You can include a Matplotlib figure as an attachment or in the HTML body without any effort:

# 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
    }
)

The library (hopefully) should be all you need from an email sender. You can install it from PyPI:

pip install redmail

Documentation: https://red-mail.readthedocs.io/en/latest/

Source code: https://github.com/Miksus/red-mail

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top