MIME and Email Format Handling

Python supplies the email package to handle parsing, generation, and manipulation of MIME files such as email messages, network news posts, and so on. The Python standard library also contains other modules that handle some parts of these jobs. However, the email package offers a complete and systematic approach to these important tasks. I suggest you use package email, not the older modules that partially overlap with parts of email’s functionality. Package email has nothing to do with receiving or sending email; for such tasks, see modules poplib and smtplib, covered in Email Protocols. email deals with handling messages after you receive them or before you send them.

Functions in Package email

Package email supplies two factory functions that return an instance m of class email.Message.Message. These functions rely on class email.Parser.Parser, but the factory functions are handier and simpler. Therefore, I do not cover module Parser further in this book.

message_from_string

message_from_string(s)

Builds m by parsing string s.

message_from_file

message_from_file(f)

Builds m by parsing the contents of file-like object f, which must be open for reading.

The email.Message Module

The email.Message module supplies class Message. All parts of package email make, modify, or use instances of class Message. An instance m of Message models a MIME message, including headers and a payload (data content). To create an initially empty m, call class Message with no arguments. ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.