[Tutor] Attachment to a mail message

Michael P. Reilly arcege@speakeasy.net
Wed, 24 Oct 2001 13:01:35 -0400

On Wed, Oct 24, 2001 at 09:16:08PM +0530, lonetwin wrote:
> Hey Arcege
>    Thanx a lot for those links ...I'll just go ahead and use one of them 
> ...although I'll still be waiting for someone to give me a idea of doing this 
> with the std lib modules...just so that I know.

You need to look at both MimeWriter and mimetools.  This is an example
from Breazley's "Python Essential Reference."  I added some bits to help
with your example.

import sys
import mimetools, mimetypes, MimeWriter
# Open the output file and create a MimeWriter
out = open("output.txt", "w")
writer = MimeWriter.MimeWriter(out)
# {Arcege: I added this to show your e-mail headers}
writer.addheader('From', 'tommy@hometown.net')
writer.addheader('To', 'santa@northpole.com')
writer.addheader('Subject:', 'christmas list')

# Start a multipart message

for file in sys.argv[1:]:
    subpart = writer.nextpart()  # Create a new sub-part
    # Attempt to guess the file's MIME type and encoding
    type, encoding = mimetypes.guess_type(file)
    if encoding:
        subpart.addheader("Content-encoding", encoding)
        # {Arcege: I think that this should not be indented}
        subpart.addheader("Content-transfer-encoding", "base64")
    if type:
        pout = subpartbody(type, [("name", file)])
        pout = subpartbody("text/plain", [("name", file)])
    infile = open(file, "rb")
    # Encode the raw data using base64
    mimetools.encoding(infile, pout, 'base64')

# Clean up

# {Arcege: this is for your help too} your smtplib.SMTP object
conn.sendmail('tommy@hometown.net', ('santa@northpole.com',),
    open('output.txt', 'r').read())
# {Arcege: notice the MimeWriter object is really useless for reading
# back the data}

Also, the mimetools.Message object is not easily convertable to the a
MimeWriter object (which is why the 'mimecntl' module was really created).
Both 'mimecntl' and 'mimelib' convert MIME input to MIME output and with
full modifications of the data (as one entity) between.  For example,
from the MimeWriter object, you cannot get access to, or change, the
headers that you previously set.


| Michael P. Reilly                | arcege@speakeasy.net              |
| Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html     |