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).

http://snippets.dzone.com/posts/show/2038

7 Responses to “Sending Email with Attachments in Python”

  1. Peter-Jan Randewijk Says:

    This should be included in the python help file!

  2. Sam Says:

    I agree this is very helpful!

  3. Radomir Says:

    Easier said than done, right? Well I want it to be the other way around!

  4. Daniel Says:

    I wanted to comment and thank the author, good stuff

  5. Christopher Says:

    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!!

  6. jordoncm Says:

    @Christopher Thanks for the correction. I must have messed it up when posting. I have corrected this for future use.

  7. Poor Yorick Says:

    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.

Leave a Reply

{
}