DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Send Email In Python With Text File Attachment

04.26.2007
| 23043 views |
  • submit to reddit
        // description of your code here
Send an email in python with a text attachment. You can change the attachment type by adjusting the part.startbody label in the attachment section (ie, 'image/jpg' or whatever)

import smtplib, sys, MimeWriter, StringIO, base64
import os
def mail(serverURL=None, sender='', to='', subject='', text=''):
    """
    Usage:
    mail('somemailserver.com', 'me@example.com', 'someone@example.com', 'test', 'This is a test')
    """
    message = StringIO.StringIO()
    writer = MimeWriter.MimeWriter(message)
    writer.addheader('Subject', subject)
    writer.startmultipartbody('mixed')

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

    # now add an attachment
    part = writer.nextpart()
    part.addheader('Content-Transfer-Encoding', 'base64')
    body = part.startbody('text/plain')
    base64.encode(open('myfile.txt', 'rb'), body)

    # finish off
    writer.lastpart()

    # send the mail
    smtp = smtplib.SMTP(serverURL)
    smtp.sendmail(sender, to, message.getvalue())
    smtp.quit()