Send a multipart email in Python

This short example shows how to send a mail with attachments using Python.
First, we create a Mime container using the class MimeWriter and then the message is sent using the smtplib package.

#!/usr/bin/env python
#

import smtplib, sys, MimeWriter, mimetypes, mimetools, base64
import os

import StringIO

SERVER = 'localhost'
PORT = 25

def mail(sender='', to='', subject='', text='', attachments=None):
    """
    Usage:
        mail()
    Params:
        sender: sender's email address
        to: receipient email address
        text: Email message body main part.
        attachments: list of files to attach
    """
    message = StringIO.StringIO()
    writer = MimeWriter.MimeWriter(message)
    writer.addheader('To', to)
    writer.addheader('From', sender)
    writer.addheader('Subject', subject)
    writer.addheader('MIME-Version', '1.0')
    
    writer.startmultipartbody('mixed')
    
    # start with a text/plain part
    part = writer.nextpart()
    body = part.startbody('text/plain')
    part.flushheaders()
    body.write(text)

    # now add the attachments
    if attachments is not None:
        for a in attachments:
            filename = os.path.basename(a)
            ctype, encoding = mimetypes.guess_type(a)
            if ctype is None:
                ctype = 'application/octet-stream'
                encoding = 'base64'
            elif ctype == 'text/plain':
                encoding = 'quoted-printable'
            else:
                encoding = 'base64'
                
            part = writer.nextpart()
            part.addheader('Content-Transfer-Encoding', encoding)
            body = part.startbody("%s; name=%s" % (ctype, filename))
            mimetools.encode(open(a, 'rb'), body, encoding)

    # that's all falks
    writer.lastpart()

    # send the mail
    smtp = smtplib.SMTP(SERVER, PORT)
    smtp.set_debuglevel(1)
    smtp.sendmail(sender, to, message.getvalue())
    smtp.quit()


if __name__ == "__main__":
    attach = [
        "/Users/fred/Desktop/11-03-07_1740.jpg",
        "/Users/fred/Desktop/11-03-07_1643.jpg",
        ]
    mail(sender='myself@example.net', to='mybuddy@sample.com',
         subject='Pictures from last weekend',
         text='Hey buddy look a the pictures we took last weekend.\n\n',
         attachments=attach)

#!/usr/bin/env python
#

import smtplib, sys, MimeWriter, mimetypes, mimetools, base64
import os

import StringIO

SERVER = 'localhost'
PORT = 25

def mail(sender='', to='', subject='', text='', attachments=None):
"""
Usage:
mail()
Params:
sender: sender's email address
to: receipient email address
text: Email message body main part.
attachments: list of files to attach
"""
message = StringIO.StringIO()
writer = MimeWriter.MimeWriter(message)
writer.addheader('To', to)
writer.addheader('From', sender)
writer.addheader('Subject', subject)
writer.addheader('MIME-Version', '1.0')

writer.startmultipartbody('mixed')

# start with a text/plain part
part = writer.nextpart()
body = part.startbody('text/plain')
part.flushheaders()
body.write(text)

# now add the attachments
if attachments is not None:
for a in attachments:
filename = os.path.basename(a)
ctype, encoding = mimetypes.guess_type(a)
if ctype is None:
ctype = 'application/octet-stream'
encoding = 'base64'
elif ctype == 'text/plain':
encoding = 'quoted-printable'
else:
encoding = 'base64'

part = writer.nextpart()
part.addheader('Content-Transfer-Encoding', encoding)
body = part.startbody("%s; name=%s" % (ctype, filename))
mimetools.encode(open(a, 'rb'), body, encoding)

# that's all falks
writer.lastpart()

# send the mail
smtp = smtplib.SMTP(SERVER, PORT)
smtp.set_debuglevel(1)
smtp.sendmail(sender, to, message.getvalue())
smtp.quit()


if __name__ == "__main__":
attach = [
"/Users/fred/Desktop/11-03-07_1740.jpg",
"/Users/fred/Desktop/11-03-07_1643.jpg",
]
mail(sender='myself@example.net', to='mybuddy@sample.com',
subject='Pictures from last weekend',
text='Hey buddy look a the pictures we took last weekend.\n\n',
attachments=attach)


When running this code the following email is generated.

http://fred.velvnet.com/attachments.jpg


 

Comments

Posted by: Golgoth Oct 05, 2008 @ 15:27

Thank you that's exactly what I was looking for.

Leave a message

(Required)
(Required and not displayed)
(Optional)
obfuscated letters Enter the text shown in the image