Python Matplotlib for smtplib

I am wondering if I can send mpplotlib pyplot via smtplib. I mean, after I build this data file:

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 that I 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 an image or html inside python so that I can send it via smtplib? Thanks!

+5
source share
2 answers

You can use figure.savefig() to save your graph in a file. Example when I output the graph 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 simply attach the image to your email (e.g. the recipe in this answer ).

+4
source

You can also do everything in saving memory in the BytesIO buffer and then load the payload with it:

 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) 
+11
source

Source: https://habr.com/ru/post/923884/


All Articles