How to send email with file attachment via Python
Post date: Jan 14, 2016 7:56:55 AM
I want to send some pdf files to my kindle, so here is a function you can use to send an email with attachment from Gmail.
# Send files to kindle
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
import json
def send_mail_with_attachment(send_from, send_to, subject, text, gmail_user, gmail_pwd, files=None,
server="127.0.0.1"):
assert isinstance(send_to, list)
msg = MIMEMultipart(
From=send_from,
To=COMMASPACE.join(send_to),
Date=formatdate(localtime=True),
Subject=subject
)
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
msg.attach(MIMEApplication(
fil.read(),
Content_Disposition='attachment; filename="%s"' % basename(f),
Name=basename(f)
))
try:
smtp = smtplib.SMTP("smtp.gmail.com", 587)
smtp.ehlo()
smtp.starttls()
smtp.login(gmail_user, gmail_pwd)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
print('successfully sent the mail')
except:
print("failed to send mail")
def get_credential(credential_file, account):
'''
Get the credential in order to send email.
The credential file (e.g. '.credentials') is in the following json format:
{"default": {
"user": "youraccountname"
, "pwd": "kulhsjfhuyjgdfh"
, "from": "whateverwhitelistedsender@gmail.com"
, "kindle": ["yourkindleaccount@kindle.com"]
},
"projx": {
"user": "youraccountname2"
, "pwd": "tfsdejybhsdse"
, "from": "whateverwhitelistedsender2@gmail.com"
, "kindle": ["yourkindleaccount@kindle.com"]
}
}
'''
with open(credential_file) as cred:
credentials = json.load(cred)
return credentials[account]
Here is how I use the function to send email:
send_mail_with_attachment(credential['from'], credential['kindle'], 'This is subject', 'body',
credential['user'], credential['pwd'],
['/Users/kittipat.kampa/Dropbox/research/manga_loader/20th_Century_Boys_v{0}.pdf'.format(chapter)])
I found the following resources very useful. I combine them and make the function above.
http://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-python
http://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python