The previous two articles in this series discussed connecting to the two major types of email servers and downloading messages. The task yet to be discussed is the actual sending of a message and how to represent an email message logically. In the first part of this article, we will discuss how to create the local data structure to represent an email message. The second part deals with actually connecting to an SMTP server and sending the message.
One of the major tasks you will want to accomplish when working with email messages is header manipulation. Basically, you can add, delete, modify, and list headers that are associated with an email message. Let's assume you have parsed a message as above, and the resulting “Message” objects are in the “emailMessage” object. We can now do the following actions to modify headers:
fields = emailMessage.keys() if emailMessage.has_key(‘To’): emailMessage.__delitem__(‘To’) emailMessage.__setitem__(‘To’, ‘email@example.com’) subj = emailMessage.__getitem__(‘Subject’) print “The message contains the following keys:\n” for field in fields: print field + “\n”
The preceding code grabs the header fields from the message. It then checks to see whether the message contains a “To” field. If it does, it deletes that field. Next, it sets the “To” field to the value firstname.lastname@example.org. After that, it fetches the “Subject” field and then prints out all of the field names on separate lines.
The above code is useful for fairly simple actions with email, and for many applications, this will be sufficient to accomplish the overall goal. However, the Python email library allows for the manipulation of much more complex header fields very easily. This takes place through the various “param” methods. Some headers are expected to have parameters added to allow them to carry more data in a compact fashion and to associate that data with a particular task. The standard application of this is in the “Content-type” header.
Usually, when you are working with MIME messages, the constructors for the various MIME Message objects will take care of setting the "Content-Type" header correctly, as will parsing a message using the parsing methods described above, and you won’t necessarily have to manually set this header. However, if you are defining a content type or subtype that isn’t covered by the built in Python classes, this will be important. To set a parameter, you use the “set_param” method, and to retrieve a parameter “get_param.” In addition, Python provides a ready made “set_type” which takes a string with the names of the main-type and sub-type and sets the Content-Type header appropriately.