Sending email in python

vijay swaminathan swavijay at gmail.com
Mon Jul 4 12:06:14 CEST 2011


Hi All,

I read through the smtplib and email modules of python and have come up with
a simple program to send a email as an attachment. This module sends out an
email but not as an attachment but in the body of the email.

Any problem with this code? any insight would be greatly appreciated.

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

testfile = 'test.txt'

msg = MIMEMultipart()
msg['Subject'] = 'Email with Attachment'
msg['From'] = 'swavijay at gmail.com'
msg['To'] = 'swavijay at gmail.com'

with open(testfile,'rb') as f:
    # Open the files in binary mode.  Let the MIMEImage class automatically
    # guess the specific image type.
    img = MIMEText(f.read())
    f.close()
    msg.attach(img)

try:
    s = smtplib.SMTP('localhost')
    s.sendmail(msg['From'],[msg['To']],msg.as_string())
    print 'Email with attachment sent successfully'
    s.quit()
except:
    print 'Email with attachment could not be sent !!'

-- 
Vijay Swaminathan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110704/4830dda7/attachment.html>


More information about the Python-list mailing list