[Tutor] e-mailing
Michael P. Reilly
arcege@shore.net
Thu, 6 Jul 2000 14:30:30 -0400 (EDT)
> What if I need to send a message with an attachement?
You can use the standard module, MimeWriter, or, IMO, the mimecntl
module <URL:http://starship.python.net/crew/arcege/modules/mimecntl.py>
For example with mimecntl, to include an image in an outgoing email:
>>> f = MIME_document('''\
Hi there, mom. I just wanted to tell you that I enjoyed Christmas. Thank
you for the mittens, they fit well.
''',
... type='text/plain',
... From='arcege@shore.net', To='my.mom@home.net'
... )
>>> print f.read()
>>> f['subject'] = 'Many thanks and holiday wishes' # add a header
>>> f.write('Love,\n\tMichael') # I forgot the signature
>>> from_addr = str(f['from']) # who is sending it?
>>> majortype = f['content-type'].majortype() # 'text'
>>> # send a picture
>>> imagefilename = 'card.gif'
>>> image = open(imagefilename).read()
>>> image = MIME_recoder(
... image,
... ( Field('content-type', 'image/gif', name=imagefilename),
... Field('content-length', len(image)),
... Field('content-disposition', 'attachment', filename=imagefilename),
... )
... )
>>> # now we encode it
>>> image.encode('base64')
>>> # make a new enclosing document instance
>>> # get f's headers to put into the new document
>>> f_fields = f.values()
>>> # we need to remove the content-type header field
>>> f_fields.remove('content-type')
>>> g = MIME_document( ( f, image ), fields=f_fields )
>>>
>>> from smtplib import SMTP
>>> sender = SMTP('localhost')
>>> sender.sendmail(from_addr, (str(g['to']),), str(g))
>>> sender.quit()
The MimeWriter, in my mind is a bit more complicated to create the
same.
-Arcege
--
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager | Email: arcege@shore.net |
| Salem, Mass. USA 01970 | |
------------------------------------------------------------------------