Sending Email with Attachments in Python
Here is a function to make sending email a little easier in Python.
import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
def send_mail(to, subject, text, from="", files=[], cc=[], bcc=[], server="localhost"):
assert type(to)==list
assert type(files)==list
assert type(cc)==list
assert type(bcc)==list
message = MIMEMultipart()
message['From'] = from
message['To'] = COMMASPACE.join(to)
message['Date'] = formatdate(localtime=True)
message['Subject'] = subject
message['Cc'] = COMMASPACE.join(cc)
message.attach(MIMEText(text))
for f in files:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(f, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
message.attach(part)
addresses = []
for x in to:
addresses.append(x)
for x in cc:
addresses.append(x)
for x in bcc:
addresses.append(x)
smtp = smtplib.SMTP(server)
smtp.sendmail(from, addresses, message.as_string())
smtp.close()
I got most of this code from the link below. I just cleaned it up a bit, re-prioritized the arguments and added support for both carbon copy (Cc) and blind carbon copy (Bcc).


May 22nd, 2008 at 07:36:01
This should be included in the python help file!
June 22nd, 2008 at 15:39:56
I agree this is very helpful!
March 11th, 2009 at 03:35:36
Easier said than done, right? Well I want it to be the other way around!
April 2nd, 2009 at 21:16:08
I wanted to comment and thank the author, good stuff
May 23rd, 2009 at 12:28:22
Looks like there’s a missing comma between ‘files’ and ‘cc’ in the function argument list.
But a part from this, thank you for the code! very helpful!!
June 1st, 2009 at 08:23:03
@Christopher Thanks for the correction. I must have messed it up when posting. I have corrected this for future use.
February 20th, 2010 at 18:24:00
I came to this page while looking for a drop-in replacement for sendmail to use with mutt. I ended up writing this:
http://www.ynform.org/w/Pub/SendmailPy
Posting it here for others who are looking for the same thing. It can also augment the above script with more automated transport mechanism.