B
B
blizzard2019-03-04 22:02:22
Python
blizzard, 2019-03-04 22:02:22

How to add an image from sqlite3 to the email body?

There is this code

import sqlite3
import smtplib

conn = sqlite3.connect('employees.sqlite')
cursor = conn.cursor()
cursor.execute(
    "SELECT id, LastName, FirstName, Photo from employees WHERE strftime('%m',DOB) = strftime('%m','now') AND  strftime('%d','now') = strftime('%d', DOB)")

results = cursor.fetchall()

conn.close()
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.starttls()
smtpObj.login('**********@gmail.com', '**********')
for empl in results:
    subject = "День рождения сотрудника"
    body = "Поздавляем сотрудника " + empl[1] + " " + empl[2] + " с Днем Рождения!"
    message = 'Subject: {}\n\n{}'.format(subject, body)

    text_encoded = message.encode('utf-8').strip()
    smtpObj.sendmail("[email protected]", "[email protected]", text_encoded)

A picture is stored in the "Photo" field. Upon request, I receive it in the form of binary data.
How can I convert this binary data back into a picture and put it in the body of the letter, which is below in the code?
I found that you can convert it back to a picture using pickle, but I still don’t understand how to do it in my case.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
st0ne_c0ld, 2019-03-05
@s41blizzard

It is not necessary to construct a letter by hand, you can take the email module and an example from the documentation:
docs.python.org/3/library/email.examples.html
or try this:

# your code above...
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()

for empl in results:
    subject = "День рождения сотрудника"
    body = "Поздавляем сотрудника " + empl[1] + " " + empl[2] + " с Днем Рождения!"
    attach = results[3]
    msg['Subject'] = subject
    msg['From'] = '[email protected]'
    msg['To'] = '[email protected]'
    #
    text = MIMEText(body.encode('utf-8').strip())
    msg.attach(text)
    image = MIMEImage(img_data, attach)
    msg.attach(image)
    smtpObj.sendmail(msg['From'],msg['To'],msg.as_string())

smtpObj.quit()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question