简体   繁体   中英

Sending Created Plot via Mail

I Used MySQLdb to built up the connection to my SQL database. Then I limited the database with

Cursor = connection.cursor()
anz = Cursor.execute(myquery)

Then I Made a Dataframe out of it

df = DataFrame(anz, columns = ['likeval','count'])

Then I plotted it

df.plot(kind='hist', x='Anzahl', y='count')

I imported MySQLdb, pandas and matplotlib.pyplot

So now I want to know how I send this plot via e-mail to someone. I want to do it with the same Code and don't want to save the graph.

First, you'll want to save the figure to a virtual file object:

import io

img_format = 'png'

df.plot(...)

f = io.BytesIO()
plt.savefig(f, format=img_format)
f.seek(0)

Now, f contains the image data and can be read from like a file:

img_data = f.read()

Next, let's create the email message:

import smtplib
from email.message import EmailMessage

msg = EmailMessage()
# Add From/To/Subject fields by using msg like a dictionary

There are two options for sending the image by email:

  1. Base64-encode it and pass it inside inside an HTML <img> tag
  2. Add it as an attachment

Option 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>''')

Option 2:

msg.add_attachment(img_data, maintype='image', subtype=img_format)

Finally, send the email:

import smtplib

s = smtplib.SMTP('localhost')
s.starttls()
s.login(...)
s.sendmail(msg['From'], [msg['To']], msg.as_string())
s.quit()

Note: I haven't tested these but they shouldn't be too far from working.

Tried option 2, works for me. Sent a matplotlib table. The header row from the table is missing though in the sent email message. Figuring that out now along with adding a subject.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM