[Tutor] Attachment to a mail message

Michael P. Reilly arcege@speakeasy.net
Wed, 24 Oct 2001 09:17:22 -0400


On Wed, Oct 24, 2001 at 06:00:27PM +0530, lonetwin wrote:
> Hi all,
>    I have a lil' question, how does one send a mail alongwith an
> attachment using python ?? I already know that one can do a
> 
> import smtplib
> conn = smtplib.SMTP(Server)
> conn.sendmail(From, To_addr, Msg)
> 
> to send Msg to To_addr, thru' Server....
> ....I'd like to learn how to add an attachment (MIME encoded ??) to this Msg,
> so that I can send mail with attachments confirming to mail standards on the net.

Hi there,

The existing MIME modules are not all that useful.  There are two
additional third party modules that do the job for you: mimecntl (at
http://starship.python.net/crew/arcege/modules/mimecntl.html) and mimelib
(at http://mimelib.sourceforge.net/).

With both, you can create MIME documents that can be sent as-is through
smtplib.

For example:

# MIME_document is the base class, MIME_recoder_f is specialized to
# encode large data to an external temporary file
from mimecntl import MIME_document, MIME_recoder_f, MIMEField

# make some text to go with the attachment
mail_body = MIME_document("""\
Hey there,  this is the picture from July 4th that you wished to see.
""")

# now load in the picture; basic data objects are treated as files
# so we read binary data blocks and write them to the MIME object
jpeg_file = open('fireworks.jpg', 'rb')
# we create a new encodable object, with a "content-type" of a JPEG
# image, and the name of the file
attachment = MIME_recoder_f(
  type=MIMEField('Content-Type', 'image/jpeg', name='fireworks.jpg')
)
jpeg_length = 0
block = jpeg_file.read(1024)
while block:
  jpeg_length = jpeg_length + len(block)
  attachment.write(block)
  block = jpeg_file.read(1024)

# but we want to encode in base64
encoded_attachment = attachment.encode('base64')
# the system does not add fields itself, it only does what you want
encoded_attachment['Content-Length'] = jpeg_length

# now combine them together into a multipart document
message = MIME_document( (mail_body, attachment),
  From=From, To=To_addr, Subject="Fourth of July Fireworks"
)

# send the document through your smtplib.SMTP object
conn.sendmail(
  message['from'],       # the "From" field of the message
  tuple(message['to']),  # multiple items in field (sendmail wants a tuple)
  str(message)           # the message as a complete string document
)

I hope this helps.
  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |