MIME control module

MIME_document

Constructor

MIME_document(data='', fields=(), type=None, encoding=None, NoVersion=0, ...)
data
Data has one of the following forms:
  1. another instance of the class or a subclass, all data is copied;
  2. a file object containing a MIME document, shorthand for the "load" method;
  3. data parts:
    1. if data is a sequence other than a string, then make the document multipart, if the items in the sequence are not MIME documents, then make instances of the same class,
    2. otherwise the data is assumed to be the message body.
    In data mode (3), header fields are entered as keyword arguments or as Field instances in the second argument.
fields
sequence of Field instances or formatted header fields.
type
content-type value, instance of MIMEField or a string.
encoding
content-transfer-encoding value
NoVersion
if 1, do not add MIME-Version field, default is 0
**kwargs
other header fields, keywords are field names
By default, if no "MIME-Version" header exists, one is added. This can be prevented by passing NoVersion=1 to the constructor or the load() method.

Operations

if self:
always true
len(self)
composite
number of items (message/* types are always one)
other
byte length of body
self[index]
index is string
return header or KeyError
composite
returns item in list
other
raise MimeError
self[index] = data
index is string
set header
index is Field instance
set header (with index modified by data)
composite
replace item in list
other
raise MimeError
del self[index]
index is string
remove header
index is Field instance
remove header
composite
remove item in list
other
raise MimeError
self[lo:hi]
composite
return items in list
other
raise MimeError
self[lo:hi] = [data]
composite
replace items in list
other
raise MimeError
del self[lo:hi]
composite
remove items in list
other
raise MimeError
str(self)
return string representation (see dump method below)

Methods

self.append(data)
multipart
append data (as instance) to list
message
call method on enclosing instance
other
raise MimeError
self.insert(pos, data)
multipart
insert data (as instance) to list
message
call method on enclosing instance
other
raise MimeError
self.remove(data)
multipart
remove data from list
message
call method on enclosing instance
other
raise MimeError
self.reverse(data)
multipart
reverse order of subparts
message
call method on enclosing instance
other
raise MimeError
self.items()
return (ordered) name, field pairs of headers
self.keys()
return (ordered) header names
self.values()
return (ordered header fields (as Field or MIMEField instances)
self.has_key(name)
return true if name is a header
self.tell()
multipart
raise MimeError
message
call method on enclosed instance
other
return current position in body
self.seek(offset, whence=0)
multipart
raise MimeError
message
call method on enclosed instance
other
change current position in body
self.read(size=-1)
multipart
raise MimeError
message
call method on enclosed instance
other
read from body
self.readline(size=-1)
multipart
raise MimeError
message
call method on enclosed instance
other
read line from body
self.readlines()
multipart
raise MimeError
message
call method on enclosed instance
other
read lines from body
self.write(data)
multipart
raise MimeError
message
call method on enclosed instance
other
write data into body at current position
self.writelines(lines)
multipart
raise MimeError
message
call method on enclosed instance
other
write lines into body at current position
self.truncate(size=0)
multipart
raise MimeError
message
call method on enclosed instance
other
truncate the file to the size given, or the whole file
self.convert(type=None, encoding=None)
change document type based on content_type and transfer_encoding fields
self.dump(file=None)
display the entire document recursively. If a multipart and no content boundary exists, create one. If a file object is given, write the document string to the file. Otherwise return the string. (str(self) is the same as self.dump())
self.load(data, NoVersion=0)
parse the data into a MIME document and replace the existing instance data with the parsed data. If data is a file instance, read the file for the data.

MIME_document_f

A specialization of the MIME_document class where the internal structure for the data is stored as a temporary file instead of a memory file.

Recoder_mixin

This is a mix-in class, adding only decode and encode methods.

Decode and encode calls are propagated to subparts for composite documents.

Methods

self.decode(encoding=None)
Decode from the "content-transfer-encoding" value, or the given value. The instance is left untouched and a new, decoded object is returned.
self.encode(encoding=None)
Encode to the "content-transfer-encoding" value or the given value. The instance is left untouched and a new, encoded object is returned.

MIME_recoder

A subclass of MIME_document, mixing in the Recoder_mixin class.

MIME_recoder_f

A subclass of MIME_document_f, mixing in the Recoder_mixin class.

Field

Represents a header in a RFC822 message.

Constructor

  1. a single argument which is an instance of the class or subclass
  2. a single string which is the formatted output of the field, e.g. Field('From: arcege@shore.net')
  3. a field name and data with attributes, e.g. Field('X-MDA', '/usr/lib/sendmail', platform='unix')
Field name is case independant for all operations. Field attributes are accessed through keys, as a dictionary.

Operations

int(self)
return the field data as an integer or raise ValueError
str(self)
return the field data as a string
repr(self)
return the formatted output as in (2) above
hash(self)
hash based on the field name
cmp(self, o)
compare based on the field name

Methods

add_attr(self, d)
add a dictionary of attributes to the field
match(self, o)
compare based on the field name and data
contained_in(self, list)
determine if the instance is in the list, uses the "match" method

MIMEField

MIMEField is a subclass of Field. This class is to be used for "content-*" field data.

Methods

majortype(self)
return the major type of a MIME "content-type" field
minortype(self)
return the minor type of a MIME "content-type" field

Examples

Loading a MIME document from a file

spam = MIME_document()
spam.load(open('mail.mime', 'r'))
spam.dump(open('mail.mime', 'w'))

Creating a new MIME document

spam = 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'
  # the "From" is capitalized to not conflict with the python keyword
)
print spam.read()
spam['subject'] = 'Many thanks and holiday wishes'  # add a header
spam.seek(0, 2)
spam.write('Love,\n\tMichael')  # I forgot the signature
from_addr = str(spam['from'])   # who is sending it?
majortype = spam['content-type'].majortype()  # --> 'text'

Making a multipart

Also uses the MIME_recoder subclass.
# send a picture
imagefilename = 'card.gif'
imagedata = open(imagefilename, 'rb').read()
# use a *_f class to utilize temporary disk space instead of memory;
# we have no idea how large the image file will be, in general
image = MIME_recoder_f(
  imagedata,
  ( MIMEField('content-type', 'image/gif', name=imagefilename),
    MIMEField('content-length', len(imagedata)),
    MIMEFIeld('content-disposition', 'attachment', filename=imagefilename),
  )
)
# now we encode it
image = image.encode('base64')
# make a new enclosing document instance
# get spam's headers to put into the new document
spam_fields = spam.values()
# we need to remove the content-type header field
spam_fields.remove('content-type')
email_for_mom = MIME_document( (spam, image), fields=spam_fields)

Sending a document in email

import smtplib
mail = smtplib.SMTP('localhost')
mail.sendmail(
  email_for_mom['from'],
  tuple(email_for_mom['to']),
  str(email_for_mom)
)
mail.quit()

Author: Michael P. Reilly (Arcege)
Website: http://www.shore.net/~arcege
Python modules: http://starship.python.net/crew/arcege