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

One Response to “Sending Email with Attachments in Python”

  1. Peter-Jan Randewijk Says:

    This should be included in the python help file!

Leave a Reply

{
}