Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 1 | % Copyright (C) 2001 Python Software Foundation |
| 2 | % Author: barry@zope.com (Barry Warsaw) |
| 3 | |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 4 | \section{\module{email} --- |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 5 | An email and MIME handling package} |
| 6 | |
| 7 | \declaremodule{standard}{email} |
| 8 | \modulesynopsis{Package supporting the parsing, manipulating, and |
| 9 | generating email messages, including MIME documents.} |
| 10 | \moduleauthor{Barry A. Warsaw}{barry@zope.com} |
Fred Drake | 90e6878 | 2001-09-27 20:09:39 +0000 | [diff] [blame] | 11 | \sectionauthor{Barry A. Warsaw}{barry@zope.com} |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 12 | |
| 13 | \versionadded{2.2} |
| 14 | |
| 15 | The \module{email} package is a library for managing email messages, |
| 16 | including MIME and other \rfc{2822}-based message documents. It |
| 17 | subsumes most of the functionality in several older standard modules |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 18 | such as \refmodule{rfc822}, \refmodule{mimetools}, |
| 19 | \refmodule{multifile}, and other non-standard packages such as |
Barry Warsaw | 5e17d20 | 2001-11-16 22:16:04 +0000 | [diff] [blame] | 20 | \module{mimecntl}. It is specifically \emph{not} designed to do any |
| 21 | sending of email messages to SMTP (\rfc{2821}) servers; that is the |
| 22 | function of the \refmodule{smtplib} module\footnote{For this reason, |
| 23 | line endings in the \module{email} package are always native line |
| 24 | endings. The \module{smtplib} module is responsible for converting |
| 25 | from native line endings to \rfc{2821} line endings, just as your mail |
| 26 | server would be responsible for converting from \rfc{2821} line |
| 27 | endings to native line endings when it stores messages in a local |
| 28 | mailbox.}. |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 29 | |
| 30 | The primary distinguishing feature of the \module{email} package is |
| 31 | that it splits the parsing and generating of email messages from the |
| 32 | internal \emph{object model} representation of email. Applications |
| 33 | using the \module{email} package deal primarily with objects; you can |
| 34 | add sub-objects to messages, remove sub-objects from messages, |
| 35 | completely re-arrange the contents, etc. There is a separate parser |
| 36 | and a separate generator which handles the transformation from flat |
Andrew M. Kuchling | 43dc1fc | 2001-11-05 01:55:03 +0000 | [diff] [blame] | 37 | text to the object model, and then back to flat text again. There |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 38 | are also handy subclasses for some common MIME object types, and a few |
| 39 | miscellaneous utilities that help with such common tasks as extracting |
| 40 | and parsing message field values, creating RFC-compliant dates, etc. |
| 41 | |
| 42 | The following sections describe the functionality of the |
| 43 | \module{email} package. The ordering follows a progression that |
| 44 | should be common in applications: an email message is read as flat |
| 45 | text from a file or other source, the text is parsed to produce an |
| 46 | object model representation of the email message, this model is |
| 47 | manipulated, and finally the model is rendered back into |
| 48 | flat text. |
| 49 | |
| 50 | It is perfectly feasible to create the object model out of whole cloth |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 51 | --- i.e. completely from scratch. From there, a similar progression |
| 52 | can be taken as above. |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 53 | |
| 54 | Also included are detailed specifications of all the classes and |
| 55 | modules that the \module{email} package provides, the exception |
| 56 | classes you might encounter while using the \module{email} package, |
| 57 | some auxiliary utilities, and a few examples. For users of the older |
| 58 | \module{mimelib} package, from which the \module{email} package is |
Andrew M. Kuchling | 43dc1fc | 2001-11-05 01:55:03 +0000 | [diff] [blame] | 59 | descended, a section on differences and porting is provided. |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 60 | |
Barry Warsaw | 5e17d20 | 2001-11-16 22:16:04 +0000 | [diff] [blame] | 61 | \begin{seealso} |
| 62 | \seemodule{smtplib}{SMTP protocol client} |
| 63 | \end{seealso} |
| 64 | |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 65 | \subsection{Representing an email message} |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 66 | \input{emailmessage} |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 67 | |
| 68 | \subsection{Parsing email messages} |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 69 | \input{emailparser} |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 70 | |
| 71 | \subsection{Generating MIME documents} |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 72 | \input{emailgenerator} |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 73 | |
| 74 | \subsection{Creating email and MIME objects from scratch} |
| 75 | |
| 76 | Ordinarily, you get a message object tree by passing some text to a |
| 77 | parser, which parses the text and returns the root of the message |
| 78 | object tree. However you can also build a complete object tree from |
| 79 | scratch, or even individual \class{Message} objects by hand. In fact, |
| 80 | you can also take an existing tree and add new \class{Message} |
| 81 | objects, move them around, etc. This makes a very convenient |
| 82 | interface for slicing-and-dicing MIME messages. |
| 83 | |
| 84 | You can create a new object tree by creating \class{Message} |
| 85 | instances, adding payloads and all the appropriate headers manually. |
| 86 | For MIME messages though, the \module{email} package provides some |
| 87 | convenient classes to make things easier. Each of these classes |
| 88 | should be imported from a module with the same name as the class, from |
| 89 | within the \module{email} package. E.g.: |
| 90 | |
| 91 | \begin{verbatim} |
| 92 | import email.MIMEImage.MIMEImage |
| 93 | \end{verbatim} |
| 94 | |
| 95 | or |
| 96 | |
| 97 | \begin{verbatim} |
| 98 | from email.MIMEText import MIMEText |
| 99 | \end{verbatim} |
| 100 | |
| 101 | Here are the classes: |
| 102 | |
| 103 | \begin{classdesc}{MIMEBase}{_maintype, _subtype, **_params} |
| 104 | This is the base class for all the MIME-specific subclasses of |
| 105 | \class{Message}. Ordinarily you won't create instances specifically |
| 106 | of \class{MIMEBase}, although you could. \class{MIMEBase} is provided |
| 107 | primarily as a convenient base class for more specific MIME-aware |
| 108 | subclasses. |
| 109 | |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 110 | \var{_maintype} is the \mailheader{Content-Type} major type |
| 111 | (e.g. \mimetype{text} or \mimetype{image}), and \var{_subtype} is the |
| 112 | \mailheader{Content-Type} minor type |
| 113 | (e.g. \mimetype{plain} or \mimetype{gif}). \var{_params} is a parameter |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 114 | key/value dictionary and is passed directly to |
| 115 | \method{Message.add_header()}. |
| 116 | |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 117 | The \class{MIMEBase} class always adds a \mailheader{Content-Type} header |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 118 | (based on \var{_maintype}, \var{_subtype}, and \var{_params}), and a |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 119 | \mailheader{MIME-Version} header (always set to \code{1.0}). |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 120 | \end{classdesc} |
| 121 | |
Barry Warsaw | a55d132 | 2001-10-09 19:14:17 +0000 | [diff] [blame] | 122 | \begin{classdesc}{MIMEAudio}{_audiodata\optional{, _subtype\optional{, |
| 123 | _encoder\optional{, **_params}}}} |
| 124 | |
| 125 | A subclass of \class{MIMEBase}, the \class{MIMEAudio} class is used to |
| 126 | create MIME message objects of major type \mimetype{audio}. |
Barry Warsaw | dca9398 | 2001-10-09 19:37:51 +0000 | [diff] [blame] | 127 | \var{_audiodata} is a string containing the raw audio data. If this |
Barry Warsaw | a55d132 | 2001-10-09 19:14:17 +0000 | [diff] [blame] | 128 | data can be decoded by the standard Python module \refmodule{sndhdr}, |
| 129 | then the subtype will be automatically included in the |
| 130 | \mailheader{Content-Type} header. Otherwise you can explicitly specify the |
| 131 | audio subtype via the \var{_subtype} parameter. If the minor type could |
| 132 | not be guessed and \var{_subtype} was not given, then \exception{TypeError} |
| 133 | is raised. |
| 134 | |
| 135 | Optional \var{_encoder} is a callable (i.e. function) which will |
| 136 | perform the actual encoding of the audio data for transport. This |
| 137 | callable takes one argument, which is the \class{MIMEAudio} instance. |
| 138 | It should use \method{get_payload()} and \method{set_payload()} to |
| 139 | change the payload to encoded form. It should also add any |
| 140 | \mailheader{Content-Transfer-Encoding} or other headers to the message |
| 141 | object as necessary. The default encoding is \emph{Base64}. See the |
| 142 | \refmodule{email.Encoders} module for a list of the built-in encoders. |
| 143 | |
| 144 | \var{_params} are passed straight through to the \class{MIMEBase} |
| 145 | constructor. |
| 146 | \end{classdesc} |
| 147 | |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 148 | \begin{classdesc}{MIMEImage}{_imagedata\optional{, _subtype\optional{, |
| 149 | _encoder\optional{, **_params}}}} |
| 150 | |
| 151 | A subclass of \class{MIMEBase}, the \class{MIMEImage} class is used to |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 152 | create MIME message objects of major type \mimetype{image}. |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 153 | \var{_imagedata} is a string containing the raw image data. If this |
| 154 | data can be decoded by the standard Python module \refmodule{imghdr}, |
| 155 | then the subtype will be automatically included in the |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 156 | \mailheader{Content-Type} header. Otherwise you can explicitly specify the |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 157 | image subtype via the \var{_subtype} parameter. If the minor type could |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 158 | not be guessed and \var{_subtype} was not given, then \exception{TypeError} |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 159 | is raised. |
| 160 | |
| 161 | Optional \var{_encoder} is a callable (i.e. function) which will |
| 162 | perform the actual encoding of the image data for transport. This |
| 163 | callable takes one argument, which is the \class{MIMEImage} instance. |
| 164 | It should use \method{get_payload()} and \method{set_payload()} to |
| 165 | change the payload to encoded form. It should also add any |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 166 | \mailheader{Content-Transfer-Encoding} or other headers to the message |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 167 | object as necessary. The default encoding is \emph{Base64}. See the |
| 168 | \refmodule{email.Encoders} module for a list of the built-in encoders. |
| 169 | |
| 170 | \var{_params} are passed straight through to the \class{MIMEBase} |
| 171 | constructor. |
| 172 | \end{classdesc} |
| 173 | |
| 174 | \begin{classdesc}{MIMEText}{_text\optional{, _subtype\optional{, |
| 175 | _charset\optional{, _encoder}}}} |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 176 | |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 177 | A subclass of \class{MIMEBase}, the \class{MIMEText} class is used to |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 178 | create MIME objects of major type \mimetype{text}. \var{_text} is the |
| 179 | string for the payload. \var{_subtype} is the minor type and defaults |
| 180 | to \mimetype{plain}. \var{_charset} is the character set of the text and is |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 181 | passed as a parameter to the \class{MIMEBase} constructor; it defaults |
| 182 | to \code{us-ascii}. No guessing or encoding is performed on the text |
| 183 | data, but a newline is appended to \var{_text} if it doesn't already |
| 184 | end with a newline. |
| 185 | |
| 186 | The \var{_encoding} argument is as with the \class{MIMEImage} class |
| 187 | constructor, except that the default encoding for \class{MIMEText} |
| 188 | objects is one that doesn't actually modify the payload, but does set |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 189 | the \mailheader{Content-Transfer-Encoding} header to \code{7bit} or |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 190 | \code{8bit} as appropriate. |
| 191 | \end{classdesc} |
| 192 | |
| 193 | \begin{classdesc}{MIMEMessage}{_msg\optional{, _subtype}} |
| 194 | A subclass of \class{MIMEBase}, the \class{MIMEMessage} class is used to |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 195 | create MIME objects of main type \mimetype{message}. \var{_msg} is used as |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 196 | the payload, and must be an instance of class \class{Message} (or a |
| 197 | subclass thereof), otherwise a \exception{TypeError} is raised. |
| 198 | |
| 199 | Optional \var{_subtype} sets the subtype of the message; it defaults |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 200 | to \mimetype{rfc822}. |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 201 | \end{classdesc} |
| 202 | |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 203 | \subsection{Encoders} |
| 204 | \input{emailencoders} |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 205 | |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 206 | \subsection{Exception classes} |
| 207 | \input{emailexc} |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 208 | |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 209 | \subsection{Miscellaneous utilities} |
| 210 | \input{emailutil} |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 211 | |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 212 | \subsection{Iterators} |
| 213 | \input{emailiter} |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 214 | |
| 215 | \subsection{Differences from \module{mimelib}} |
| 216 | |
| 217 | The \module{email} package was originally prototyped as a separate |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 218 | library called |
| 219 | \ulink{\module{mimelib}}{http://mimelib.sf.net/}. |
| 220 | Changes have been made so that |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 221 | method names are more consistent, and some methods or modules have |
| 222 | either been added or removed. The semantics of some of the methods |
| 223 | have also changed. For the most part, any functionality available in |
Fred Drake | 90e6878 | 2001-09-27 20:09:39 +0000 | [diff] [blame] | 224 | \module{mimelib} is still available in the \refmodule{email} package, |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 225 | albeit often in a different way. |
| 226 | |
| 227 | Here is a brief description of the differences between the |
Fred Drake | 90e6878 | 2001-09-27 20:09:39 +0000 | [diff] [blame] | 228 | \module{mimelib} and the \refmodule{email} packages, along with hints on |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 229 | how to port your applications. |
| 230 | |
| 231 | Of course, the most visible difference between the two packages is |
Fred Drake | 90e6878 | 2001-09-27 20:09:39 +0000 | [diff] [blame] | 232 | that the package name has been changed to \refmodule{email}. In |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 233 | addition, the top-level package has the following differences: |
| 234 | |
| 235 | \begin{itemize} |
| 236 | \item \function{messageFromString()} has been renamed to |
| 237 | \function{message_from_string()}. |
| 238 | \item \function{messageFromFile()} has been renamed to |
| 239 | \function{message_from_file()}. |
| 240 | \end{itemize} |
| 241 | |
| 242 | The \class{Message} class has the following differences: |
| 243 | |
| 244 | \begin{itemize} |
| 245 | \item The method \method{asString()} was renamed to \method{as_string()}. |
| 246 | \item The method \method{ismultipart()} was renamed to |
| 247 | \method{is_multipart()}. |
| 248 | \item The \method{get_payload()} method has grown a \var{decode} |
| 249 | optional argument. |
| 250 | \item The method \method{getall()} was renamed to \method{get_all()}. |
| 251 | \item The method \method{addheader()} was renamed to \method{add_header()}. |
| 252 | \item The method \method{gettype()} was renamed to \method{get_type()}. |
| 253 | \item The method\method{getmaintype()} was renamed to |
| 254 | \method{get_main_type()}. |
| 255 | \item The method \method{getsubtype()} was renamed to |
| 256 | \method{get_subtype()}. |
| 257 | \item The method \method{getparams()} was renamed to |
| 258 | \method{get_params()}. |
| 259 | Also, whereas \method{getparams()} returned a list of strings, |
| 260 | \method{get_params()} returns a list of 2-tuples, effectively |
Barry Warsaw | c5f8fe3 | 2001-09-26 22:21:52 +0000 | [diff] [blame] | 261 | the key/value pairs of the parameters, split on the \character{=} |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 262 | sign. |
| 263 | \item The method \method{getparam()} was renamed to \method{get_param()}. |
| 264 | \item The method \method{getcharsets()} was renamed to |
| 265 | \method{get_charsets()}. |
| 266 | \item The method \method{getfilename()} was renamed to |
| 267 | \method{get_filename()}. |
| 268 | \item The method \method{getboundary()} was renamed to |
| 269 | \method{get_boundary()}. |
| 270 | \item The method \method{setboundary()} was renamed to |
| 271 | \method{set_boundary()}. |
| 272 | \item The method \method{getdecodedpayload()} was removed. To get |
| 273 | similar functionality, pass the value 1 to the \var{decode} flag |
| 274 | of the {get_payload()} method. |
| 275 | \item The method \method{getpayloadastext()} was removed. Similar |
| 276 | functionality |
| 277 | is supported by the \class{DecodedGenerator} class in the |
| 278 | \refmodule{email.Generator} module. |
| 279 | \item The method \method{getbodyastext()} was removed. You can get |
| 280 | similar functionality by creating an iterator with |
| 281 | \function{typed_subpart_iterator()} in the |
| 282 | \refmodule{email.Iterators} module. |
| 283 | \end{itemize} |
| 284 | |
| 285 | The \class{Parser} class has no differences in its public interface. |
| 286 | It does have some additional smarts to recognize |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 287 | \mimetype{message/delivery-status} type messages, which it represents as |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 288 | a \class{Message} instance containing separate \class{Message} |
| 289 | subparts for each header block in the delivery status |
| 290 | notification\footnote{Delivery Status Notifications (DSN) are defined |
Fred Drake | 90e6878 | 2001-09-27 20:09:39 +0000 | [diff] [blame] | 291 | in \rfc{1894}.}. |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 292 | |
| 293 | The \class{Generator} class has no differences in its public |
| 294 | interface. There is a new class in the \refmodule{email.Generator} |
| 295 | module though, called \class{DecodedGenerator} which provides most of |
| 296 | the functionality previously available in the |
| 297 | \method{Message.getpayloadastext()} method. |
| 298 | |
| 299 | The following modules and classes have been changed: |
| 300 | |
| 301 | \begin{itemize} |
| 302 | \item The \class{MIMEBase} class constructor arguments \var{_major} |
| 303 | and \var{_minor} have changed to \var{_maintype} and |
| 304 | \var{_subtype} respectively. |
| 305 | \item The \code{Image} class/module has been renamed to |
| 306 | \code{MIMEImage}. The \var{_minor} argument has been renamed to |
| 307 | \var{_subtype}. |
| 308 | \item The \code{Text} class/module has been renamed to |
| 309 | \code{MIMEText}. The \var{_minor} argument has been renamed to |
| 310 | \var{_subtype}. |
| 311 | \item The \code{MessageRFC822} class/module has been renamed to |
| 312 | \code{MIMEMessage}. Note that an earlier version of |
| 313 | \module{mimelib} called this class/module \code{RFC822}, but |
| 314 | that clashed with the Python standard library module |
| 315 | \refmodule{rfc822} on some case-insensitive file systems. |
| 316 | |
| 317 | Also, the \class{MIMEMessage} class now represents any kind of |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 318 | MIME message with main type \mimetype{message}. It takes an |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 319 | optional argument \var{_subtype} which is used to set the MIME |
Fred Drake | a6a885b | 2001-09-26 16:52:18 +0000 | [diff] [blame] | 320 | subtype. \var{_subtype} defaults to \mimetype{rfc822}. |
Barry Warsaw | 5e63463 | 2001-09-26 05:23:47 +0000 | [diff] [blame] | 321 | \end{itemize} |
| 322 | |
| 323 | \module{mimelib} provided some utility functions in its |
| 324 | \module{address} and \module{date} modules. All of these functions |
| 325 | have been moved to the \refmodule{email.Utils} module. |
| 326 | |
| 327 | The \code{MsgReader} class/module has been removed. Its functionality |
| 328 | is most closely supported in the \function{body_line_iterator()} |
| 329 | function in the \refmodule{email.Iterators} module. |
| 330 | |
| 331 | \subsection{Examples} |
| 332 | |
Barry Warsaw | 2bb077f | 2001-11-05 17:50:53 +0000 | [diff] [blame] | 333 | Here are a few examples of how to use the \module{email} package to |
| 334 | read, write, and send simple email messages, as well as more complex |
| 335 | MIME messages. |
| 336 | |
| 337 | First, let's see how to create and send a simple text message: |
| 338 | |
| 339 | \begin{verbatim} |
| 340 | # Import smtplib for the actual sending function |
| 341 | import smtplib |
| 342 | |
| 343 | # Here are the email pacakge modules we'll need |
| 344 | from email import Encoders |
| 345 | from email.MIMEText import MIMEText |
| 346 | |
| 347 | # Open a plain text file for reading |
| 348 | fp = open(textfile) |
| 349 | # Create a text/plain message, using Quoted-Printable encoding for non-ASCII |
| 350 | # characters. |
| 351 | msg = MIMEText(fp.read(), _encoder=Encoders.encode_quopri) |
| 352 | fp.close() |
| 353 | |
| 354 | # me == the sender's email address |
| 355 | # you == the recipient's email address |
Fred Drake | 928051f | 2002-02-15 04:12:59 +0000 | [diff] [blame] | 356 | msg['Subject'] = 'The contents of %s' % textfile |
Barry Warsaw | 2bb077f | 2001-11-05 17:50:53 +0000 | [diff] [blame] | 357 | msg['From'] = me |
| 358 | msg['To'] = you |
| 359 | |
| 360 | # Send the message via our own SMTP server. Use msg.as_string() with |
| 361 | # unixfrom=0 so as not to confuse SMTP. |
| 362 | s = smtplib.SMTP() |
| 363 | s.connect() |
| 364 | s.sendmail(me, [you], msg.as_string(0)) |
| 365 | s.close() |
| 366 | \end{verbatim} |
| 367 | |
| 368 | Here's an example of how to send a MIME message containing a bunch of |
| 369 | family pictures: |
| 370 | |
| 371 | \begin{verbatim} |
| 372 | # Import smtplib for the actual sending function |
| 373 | import smtplib |
| 374 | |
| 375 | # Here are the email pacakge modules we'll need |
| 376 | from email.MIMEImage import MIMEImage |
| 377 | from email.MIMEBase import MIMEBase |
| 378 | |
| 379 | COMMASPACE = ', ' |
| 380 | |
| 381 | # Create the container (outer) email message. |
| 382 | # me == the sender's email address |
| 383 | # family = the list of all recipients' email addresses |
| 384 | msg = MIMEBase('multipart', 'mixed') |
| 385 | msg['Subject'] = 'Our family reunion' |
| 386 | msg['From'] = me |
| 387 | msg['To'] = COMMASPACE.join(family) |
| 388 | msg.preamble = 'Our family reunion' |
| 389 | # Guarantees the message ends in a newline |
| 390 | msg.epilogue = '' |
| 391 | |
| 392 | # Assume we know that the image files are all in PNG format |
| 393 | for file in pngfiles: |
| 394 | # Open the files in binary mode. Let the MIMEIMage class automatically |
| 395 | # guess the specific image type. |
| 396 | fp = open(file, 'rb') |
| 397 | img = MIMEImage(fp.read()) |
| 398 | fp.close() |
| 399 | msg.attach(img) |
| 400 | |
| 401 | # Send the email via our own SMTP server. |
| 402 | s = smtplib.SMTP() |
| 403 | s.connect() |
| 404 | s.sendmail(me, family, msg.as_string(unixfrom=0)) |
| 405 | s.close() |
| 406 | \end{verbatim} |
| 407 | |
| 408 | Here's an example\footnote{Thanks to Matthew Dixon Cowles for the |
| 409 | original inspiration and examples.} of how to send the entire contents |
| 410 | of a directory as an email message: |
| 411 | |
| 412 | \begin{verbatim} |
| 413 | #!/usr/bin/env python |
| 414 | |
| 415 | """Send the contents of a directory as a MIME message. |
| 416 | |
| 417 | Usage: dirmail [options] from to [to ...]* |
| 418 | |
| 419 | Options: |
| 420 | -h / --help |
| 421 | Print this message and exit. |
| 422 | |
| 423 | -d directory |
| 424 | --directory=directory |
| 425 | Mail the contents of the specified directory, otherwise use the |
| 426 | current directory. Only the regular files in the directory are sent, |
| 427 | and we don't recurse to subdirectories. |
| 428 | |
| 429 | `from' is the email address of the sender of the message. |
| 430 | |
| 431 | `to' is the email address of the recipient of the message, and multiple |
| 432 | recipients may be given. |
| 433 | |
| 434 | The email is sent by forwarding to your local SMTP server, which then does the |
| 435 | normal delivery process. Your local machine must be running an SMTP server. |
| 436 | """ |
| 437 | |
| 438 | import sys |
| 439 | import os |
| 440 | import getopt |
| 441 | import smtplib |
| 442 | # For guessing MIME type based on file name extension |
| 443 | import mimetypes |
| 444 | |
| 445 | from email import Encoders |
| 446 | from email.Message import Message |
| 447 | from email.MIMEAudio import MIMEAudio |
| 448 | from email.MIMEBase import MIMEBase |
| 449 | from email.MIMEImage import MIMEImage |
| 450 | from email.MIMEText import MIMEText |
| 451 | |
| 452 | COMMASPACE = ', ' |
| 453 | |
| 454 | |
| 455 | def usage(code, msg=''): |
| 456 | print >> sys.stderr, __doc__ |
| 457 | if msg: |
| 458 | print >> sys.stderr, msg |
| 459 | sys.exit(code) |
| 460 | |
| 461 | |
| 462 | def main(): |
| 463 | try: |
| 464 | opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'directory=']) |
| 465 | except getopt.error, msg: |
| 466 | usage(1, msg) |
| 467 | |
| 468 | dir = os.curdir |
| 469 | for opt, arg in opts: |
| 470 | if opt in ('-h', '--help'): |
| 471 | usage(0) |
| 472 | elif opt in ('-d', '--directory'): |
| 473 | dir = arg |
| 474 | |
| 475 | if len(args) < 2: |
| 476 | usage(1) |
| 477 | |
| 478 | sender = args[0] |
| 479 | recips = args[1:] |
| 480 | |
| 481 | # Create the enclosing (outer) message |
| 482 | outer = MIMEBase('multipart', 'mixed') |
Fred Drake | 928051f | 2002-02-15 04:12:59 +0000 | [diff] [blame] | 483 | outer['Subject'] = 'Contents of directory %s' % os.path.abspath(dir) |
Barry Warsaw | 2bb077f | 2001-11-05 17:50:53 +0000 | [diff] [blame] | 484 | outer['To'] = sender |
| 485 | outer['From'] = COMMASPACE.join(recips) |
| 486 | outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' |
| 487 | # To guarantee the message ends with a newline |
| 488 | outer.epilogue = '' |
| 489 | |
| 490 | for filename in os.listdir(dir): |
| 491 | path = os.path.join(dir, filename) |
| 492 | if not os.path.isfile(path): |
| 493 | continue |
| 494 | # Guess the Content-Type: based on the file's extension. Encoding |
| 495 | # will be ignored, although we should check for simple things like |
| 496 | # gzip'd or compressed files |
| 497 | ctype, encoding = mimetypes.guess_type(path) |
| 498 | if ctype is None or encoding is not None: |
| 499 | # No guess could be made, or the file is encoded (compressed), so |
| 500 | # use a generic bag-of-bits type. |
| 501 | ctype = 'application/octet-stream' |
| 502 | maintype, subtype = ctype.split('/', 1) |
| 503 | if maintype == 'text': |
| 504 | fp = open(path) |
| 505 | # Note: we should handle calculating the charset |
| 506 | msg = MIMEText(fp.read(), _subtype=subtype) |
| 507 | fp.close() |
| 508 | elif maintype == 'image': |
| 509 | fp = open(path, 'rb') |
| 510 | msg = MIMEImage(fp.read(), _subtype=subtype) |
| 511 | fp.close() |
| 512 | elif maintype == 'audio': |
| 513 | fp = open(path, 'rb') |
| 514 | msg = MIMEAudio(fp.read(), _subtype=subtype) |
| 515 | fp.close() |
| 516 | else: |
| 517 | fp = open(path, 'rb') |
| 518 | msg = MIMEBase(maintype, subtype) |
| 519 | msg.add_payload(fp.read()) |
| 520 | fp.close() |
| 521 | # Encode the payload using Base64 |
| 522 | Encoders.encode_base64(msg) |
| 523 | # Set the filename parameter |
| 524 | msg.add_header('Content-Disposition', 'attachment', filename=filename) |
| 525 | outer.attach(msg) |
| 526 | |
| 527 | fp = open('/tmp/debug.pck', 'w') |
| 528 | import cPickle |
| 529 | cPickle.dump(outer, fp) |
| 530 | fp.close() |
| 531 | # Now send the message |
| 532 | s = smtplib.SMTP() |
| 533 | s.connect() |
| 534 | s.sendmail(sender, recips, outer.as_string(0)) |
| 535 | s.close() |
| 536 | |
| 537 | |
| 538 | if __name__ == '__main__': |
| 539 | main() |
| 540 | \end{verbatim} |
| 541 | |
| 542 | And finally, here's an example of how to unpack a MIME message like |
| 543 | the one above, into a directory of files: |
| 544 | |
| 545 | \begin{verbatim} |
| 546 | #!/usr/bin/env python |
| 547 | |
| 548 | """Unpack a MIME message into a directory of files. |
| 549 | |
| 550 | Usage: unpackmail [options] msgfile |
| 551 | |
| 552 | Options: |
| 553 | -h / --help |
| 554 | Print this message and exit. |
| 555 | |
| 556 | -d directory |
| 557 | --directory=directory |
| 558 | Unpack the MIME message into the named directory, which will be |
| 559 | created if it doesn't already exist. |
| 560 | |
| 561 | msgfile is the path to the file containing the MIME message. |
| 562 | """ |
| 563 | |
| 564 | import sys |
| 565 | import os |
| 566 | import getopt |
| 567 | import errno |
| 568 | import mimetypes |
| 569 | import email |
| 570 | |
| 571 | |
| 572 | def usage(code, msg=''): |
| 573 | print >> sys.stderr, __doc__ |
| 574 | if msg: |
| 575 | print >> sys.stderr, msg |
| 576 | sys.exit(code) |
| 577 | |
| 578 | |
| 579 | def main(): |
| 580 | try: |
| 581 | opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'directory=']) |
| 582 | except getopt.error, msg: |
| 583 | usage(1, msg) |
| 584 | |
| 585 | dir = os.curdir |
| 586 | for opt, arg in opts: |
| 587 | if opt in ('-h', '--help'): |
| 588 | usage(0) |
| 589 | elif opt in ('-d', '--directory'): |
| 590 | dir = arg |
| 591 | |
| 592 | try: |
| 593 | msgfile = args[0] |
| 594 | except IndexError: |
| 595 | usage(1) |
| 596 | |
| 597 | try: |
| 598 | os.mkdir(dir) |
| 599 | except OSError, e: |
| 600 | # Ignore directory exists error |
| 601 | if e.errno <> errno.EEXIST: raise |
| 602 | |
| 603 | fp = open(msgfile) |
| 604 | msg = email.message_from_file(fp) |
| 605 | fp.close() |
| 606 | |
| 607 | counter = 1 |
| 608 | for part in msg.walk(): |
| 609 | # multipart/* are just containers |
| 610 | if part.get_main_type() == 'multipart': |
| 611 | continue |
| 612 | # Applications should really sanitize the given filename so that an |
| 613 | # email message can't be used to overwrite important files |
| 614 | filename = part.get_filename() |
| 615 | if not filename: |
| 616 | ext = mimetypes.guess_extension(part.get_type()) |
| 617 | if not ext: |
| 618 | # Use a generic bag-of-bits extension |
| 619 | ext = '.bin' |
Fred Drake | 928051f | 2002-02-15 04:12:59 +0000 | [diff] [blame] | 620 | filename = 'part-%03d%s' % (counter, ext) |
Barry Warsaw | 2bb077f | 2001-11-05 17:50:53 +0000 | [diff] [blame] | 621 | counter += 1 |
| 622 | fp = open(os.path.join(dir, filename), 'wb') |
| 623 | fp.write(part.get_payload(decode=1)) |
| 624 | fp.close() |
| 625 | |
| 626 | |
| 627 | if __name__ == '__main__': |
| 628 | main() |
| 629 | \end{verbatim} |