Using smtplib
Gary Herron
gherron at aw.sgi.com
Fri Mar 10 13:40:54 EST 2000
Pieter Claerhout wrote:
>
> Hello,
>
> does anyone has an example on how to send an email using the
> smtplib? I'm able to send an email, but I can't figure out how to
> fill in the from, subject and to fields.
>
> Thanks,
>
> Pieter
Here is a small example. It uses the MimeWriter module to get the
headers and body correctly into the final message string. It's a slight
overkill, but my real project extended this a bit to include several
binary file attachments. In that case, MimeWritter was very helpful.
Gary.
--
Dr. Gary Herron <gherron at aw.sgi.com>
206-287-5616
Alias | Wavefront
1218 3rd Ave, Suite 800, Seattle WA 98101
-------------- next part --------------
""" Here is a small example which used MimeWriter to create a message
body with the proper headers, and smtplib to mail it. MimeWriter can
be used build a message with any type of atachments, but that's
another example. """
import string, time, smtplib, MimeWriter, StringIO
# Current date and time in (probably) the "right" format.
date = time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime(time.time()))
timezone = ' %+03d%02d' % (-time.timezone/3600, time.timezone%3600)
# Various parameters:
fromName = 'My Name'
fromAddress = 'me at some.where.com'
toAddress = 'me at some.where.com'
subject = 'This is a test'
body = 'This is only a test. Had it been a real message, ...'
# Message will be built up into a StringIO object:
msgObj = StringIO.StringIO()
# Build the message, headers and all.
# See http://info.internet.isi.edu/in-notes/rfc/files/rfc822.txt for
# more than you ever wanted to know about mail headers.
mimeObj = MimeWriter.MimeWriter(msgObj)
mimeObj.addheader('From', '%s <%s>' % (fromName,fromAddress))
mimeObj.addheader('Date', date+timezone)
mimeObj.addheader('To', toAddress)
mimeObj.addheader('Subject', subject)
mimeObj.addheader('Content-Transfer-Encoding', '7bit')
bodyWriter = mimeObj.startbody('text/plain; charset=us-ascii')
bodyWriter.write(body)
# Now send the message.
person,host = string.split(toAddress, '@')
sendmailObj = smtplib.SMTP(host)
returncode = sendmailObj.sendmail(fromAddress, toAddress, msgObj.getvalue())
if returncode:
print 'Sendmail ***FAILED:', returncode
else:
print 'Sendmail succeeded'
More information about the Python-list
mailing list