Python--Sending a email with a attachment
<p>I am working on a big project, that includes a database for remembering users. il skip the details, but my client wants me to include a function by wich he can backup all the user data and other files.</p>

<p>I was thinking of a email, (since the project is a android app) and I was trying to figure out how you could send a attachement (i.e a .db sqlite3 file) in a email. I know theres alot of similair questions around over <a href="http://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-pytho">here</a>, but all of the answers to <a href="http://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-pytho">this</a> question gives me a error. here is the closest that I got:</p>

<p>This program sends a email without a attachment:</p>

<pre><code>import smtplib

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

boodskap = MIMEText("Toekomsweb Epos toets", 'plain')

van_adres = "from adres"

na_adres = "to adres"

epos_liggaam = MIMEMultipart('alternatief')

epos_liggaam['Subject'] = "Toets"

epos_liggaam['From'] = van_adres

epos_liggaam['To'] = na_adres

epos_liggaam.attach(boodskap)

mail = smtplib.SMTP('smtp.gmail.com',587)

mail.ehlo()

mail.starttls()

mail.login(van_adres,'PASSWORD')

mail.sendmail(van_adres,na_adres,epos_liggaam.as_string())

mail.close()
print("succes!")
</code></pre>

<p>please excuse my poor variable naming, its not in english.</p>

<p>any help on sending a attachment? </p>

<p>Thanks!</p>

<p>Hi this is the code I used... it turns out that ubunto uses a different way of sending a email than windows.</p>

<pre><code>import smtplib

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

from email.mime.base import MIMEBase

from email import encoders

import os

boodskap = MIMEText("Toekomsweb Epos toets", 'plain')

van_adres = 'From adres'

na_adres = 'To adres'

epos_liggaam = MIMEMultipart('alternatief')

epos_liggaam['Subject'] = "Toets"

epos_liggaam['From'] = van_adres

epos_liggaam['To'] = na_adres

epos_liggaam.attach(boodskap)

f = "toets.db"
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f)))
epos_liggaam.attach(part)

mail = smtplib.SMTP('smtp.gmail.com',587)

mail.ehlo()

mail.starttls()

mail.login(van_adres,'PASSWORD')

mail.sendmail(van_adres,na_adres,epos_liggaam.as_string())

mail.close()
print("succes!")
</code></pre>

<p>this answer was adapted from <a href="http://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-python">here</a> (second answer)</p>

<p>hope that this answer will answer other people's question aswell</p>

python python-2.7 email smtplib