Python: Send mail with attachment ( Any file format)

So you want to send mail with any file as attachment. This script works with any type of attachment. I have given the example of .kml file, an unusual one. You can use pdf, docx etc.



import mimetypes
import email
import email.mime.application
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib

# Create a text/plain message
msg = email.mime.Multipart.MIMEMultipart()
msg['Subject'] = 'Groove'
msg['From'] = 'mysender@gmail.com'
msg['To'] = 'receiver@gmail.com'

# The main body is just another attachment
body = email.mime.Text.MIMEText("""Hello, how are you? """)
msg.attach(body)

# KML attachment
filename='cache/20140210204804.kml'
fp=open(filename,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="kml")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(att)

s = smtplib.SMTP('smtp.gmail.com')
s.starttls()
s.login('mysender@gmail.com','password')
s.sendmail('mysender@gmail.com',['receiver@gmail.com'], msg.as_string())
s.quit()

Comments