Sending e-mails with attachments.

Mikhail Astafiev mikle at tomsk.net
Fri Apr 27 13:47:23 EDT 2001


[Env: Win2k, Python 1.52]

Hi!

I'm not familiar with Python. The code below works OK excluding that
message body is empty. I've tried a lot  of variants but I'm always
getting either message without body, or message with body but attached 
zip file is corrupted! :((
May be someone can tell me how to make the code below working, i.e.
generate message with body and proper zip file attached?..

Thanks in advance.

def generate_mime_message( from_address, to_address, subject,
                         file_to_send, file_name, write_to ):
   """Generate multipart MIME message with attached file in base64 encoding
   Params: string from_address, to_address, subject
           string file_to_send - path to existent ZIP file
           string file_name - send zip with specified name
           string write_to - store completed message to this file
   Return: -"""

   try:
    fp=open( write_to, "wc")
   except(Exception),err:
    print "can't open file for writing '%s':%s. Abnormal function termination"%(write_to,err))
    return

   toplevel=MimeWriter.MimeWriter(fp)

   toplevel.addheader("Date", time.ctime(time.time()))
   toplevel.addheader("From", from_address )
   toplevel.addheader("To",  to_address )
   toplevel.addheader("Subject" , subject )
   toplevel.addheader("MIME-Version", "1.0")
   toplevel.addheader("X-Mailer" , XMAILER )
   toplevel.flushheaders()

   f=toplevel.startmultipartbody("mixed",
                                mimetools.choose_boundary(),
                                prefix=0)

   f.write("MESSAGE_BODY")

   # first toplevel body part
   mfp = toplevel.nextpart()

   mfp.addheader("Content-Transfer-Encoding", "base64")
   mfp.addheader("Content-Disposition",
               "attachment;  filename=\"%s\""%file_name)

   m = MimeWriter.MimeWriter (mfp.startbody("application/zip"))

   try:
    fpin=open( file_to_send , "rb")
    base64.encode(fpin, f )
    fpin.close()
   except(Exception),err:
    print "can't open file '%s' to send:%s. Empty section created!"%(file_to_send,err))

   toplevel.lastpart()
   fp.close()






More information about the Python-list mailing list