[Tutor] Te: [Tutor] Email Attachment

Michael P. Reilly arcege@shore.net
Wed, 2 Jun 1999 11:29:00 -0400 (EDT)


> Hi,
> 
>  How do I write a script that send a email with attachment (ascii or
> binary), tried smtplib but doesn't support attachment, tried
> MimeWriter.py but couldn't send mail. Just need a simple component or
> wrapper to do the job, please help or any useful links.
> 
> Thanks
> 

I would suggest a combination of (c)StringIO, smtplib and MimeWriter.

from smtplib import SMTP
from MimeWriter import MimeWriter
try:
  from cStringIO import StringIO
except ImportError:
  from StringIO import StringIO

tempfile = StringIO()
mw = MimeWriter(tempfile)
mw.addheader('to', 'tutor@python.org')
mw.addheader('from', 'arcege@shore.net')
mw.addheader('subject', '[Tutor] Email attachment')
mw.startmultipartbody('mixed')
for filename in files_to_attach:
  sw = mw.nextpart()
  f = sw.startbody('application/x-python')
  f.write(open(filename).read())
mw.lastpart()

message = tempfile.getvalue()
SMTP('mailhost').sendmail('arcege@shore.net', 'tutor@python.org', message)

Gee, I hope I haven't given too much of the fun stuff away. :)

You can also look at my mimecntl module to do some more of this for you.
(http://www.shore.net/~arcege/python/mimecntl.py)

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Engineer | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------