blob: 400ea1521190eb82ef51c455de7b4f99cc6cd33e [file] [log] [blame]
Barry Warsaw5e634632001-09-26 05:23:47 +00001% Copyright (C) 2001 Python Software Foundation
2% Author: barry@zope.com (Barry Warsaw)
3
Fred Drakea6a885b2001-09-26 16:52:18 +00004\section{\module{email} ---
Barry Warsaw5e634632001-09-26 05:23:47 +00005 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 Drake90e68782001-09-27 20:09:39 +000011\sectionauthor{Barry A. Warsaw}{barry@zope.com}
Barry Warsaw5e634632001-09-26 05:23:47 +000012
13\versionadded{2.2}
14
15The \module{email} package is a library for managing email messages,
16including MIME and other \rfc{2822}-based message documents. It
17subsumes most of the functionality in several older standard modules
Barry Warsawc5f8fe32001-09-26 22:21:52 +000018such as \refmodule{rfc822}, \refmodule{mimetools},
19\refmodule{multifile}, and other non-standard packages such as
Barry Warsaw5e17d202001-11-16 22:16:04 +000020\module{mimecntl}. It is specifically \emph{not} designed to do any
21sending of email messages to SMTP (\rfc{2821}) servers; that is the
22function of the \refmodule{smtplib} module\footnote{For this reason,
23line endings in the \module{email} package are always native line
24endings. The \module{smtplib} module is responsible for converting
25from native line endings to \rfc{2821} line endings, just as your mail
26server would be responsible for converting from \rfc{2821} line
27endings to native line endings when it stores messages in a local
28mailbox.}.
Barry Warsaw5e634632001-09-26 05:23:47 +000029
30The primary distinguishing feature of the \module{email} package is
31that it splits the parsing and generating of email messages from the
32internal \emph{object model} representation of email. Applications
33using the \module{email} package deal primarily with objects; you can
34add sub-objects to messages, remove sub-objects from messages,
35completely re-arrange the contents, etc. There is a separate parser
36and a separate generator which handles the transformation from flat
Andrew M. Kuchling43dc1fc2001-11-05 01:55:03 +000037text to the object model, and then back to flat text again. There
Barry Warsaw5e634632001-09-26 05:23:47 +000038are also handy subclasses for some common MIME object types, and a few
39miscellaneous utilities that help with such common tasks as extracting
40and parsing message field values, creating RFC-compliant dates, etc.
41
42The following sections describe the functionality of the
43\module{email} package. The ordering follows a progression that
44should be common in applications: an email message is read as flat
45text from a file or other source, the text is parsed to produce an
46object model representation of the email message, this model is
47manipulated, and finally the model is rendered back into
48flat text.
49
50It is perfectly feasible to create the object model out of whole cloth
Barry Warsawc5f8fe32001-09-26 22:21:52 +000051--- i.e. completely from scratch. From there, a similar progression
52can be taken as above.
Barry Warsaw5e634632001-09-26 05:23:47 +000053
54Also included are detailed specifications of all the classes and
55modules that the \module{email} package provides, the exception
56classes you might encounter while using the \module{email} package,
57some auxiliary utilities, and a few examples. For users of the older
58\module{mimelib} package, from which the \module{email} package is
Andrew M. Kuchling43dc1fc2001-11-05 01:55:03 +000059descended, a section on differences and porting is provided.
Barry Warsaw5e634632001-09-26 05:23:47 +000060
Barry Warsaw5e17d202001-11-16 22:16:04 +000061\begin{seealso}
62 \seemodule{smtplib}{SMTP protocol client}
63\end{seealso}
64
Barry Warsaw5e634632001-09-26 05:23:47 +000065\subsection{Representing an email message}
Barry Warsawc5f8fe32001-09-26 22:21:52 +000066\input{emailmessage}
Barry Warsaw5e634632001-09-26 05:23:47 +000067
68\subsection{Parsing email messages}
Barry Warsawc5f8fe32001-09-26 22:21:52 +000069\input{emailparser}
Barry Warsaw5e634632001-09-26 05:23:47 +000070
71\subsection{Generating MIME documents}
Barry Warsawc5f8fe32001-09-26 22:21:52 +000072\input{emailgenerator}
Barry Warsaw5e634632001-09-26 05:23:47 +000073
74\subsection{Creating email and MIME objects from scratch}
75
76Ordinarily, you get a message object tree by passing some text to a
77parser, which parses the text and returns the root of the message
78object tree. However you can also build a complete object tree from
79scratch, or even individual \class{Message} objects by hand. In fact,
80you can also take an existing tree and add new \class{Message}
81objects, move them around, etc. This makes a very convenient
82interface for slicing-and-dicing MIME messages.
83
84You can create a new object tree by creating \class{Message}
85instances, adding payloads and all the appropriate headers manually.
86For MIME messages though, the \module{email} package provides some
87convenient classes to make things easier. Each of these classes
88should be imported from a module with the same name as the class, from
89within the \module{email} package. E.g.:
90
91\begin{verbatim}
92import email.MIMEImage.MIMEImage
93\end{verbatim}
94
95or
96
97\begin{verbatim}
98from email.MIMEText import MIMEText
99\end{verbatim}
100
101Here are the classes:
102
103\begin{classdesc}{MIMEBase}{_maintype, _subtype, **_params}
104This is the base class for all the MIME-specific subclasses of
105\class{Message}. Ordinarily you won't create instances specifically
106of \class{MIMEBase}, although you could. \class{MIMEBase} is provided
107primarily as a convenient base class for more specific MIME-aware
108subclasses.
109
Barry Warsawc5f8fe32001-09-26 22:21:52 +0000110\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 Warsaw5e634632001-09-26 05:23:47 +0000114key/value dictionary and is passed directly to
115\method{Message.add_header()}.
116
Fred Drakea6a885b2001-09-26 16:52:18 +0000117The \class{MIMEBase} class always adds a \mailheader{Content-Type} header
Barry Warsaw5e634632001-09-26 05:23:47 +0000118(based on \var{_maintype}, \var{_subtype}, and \var{_params}), and a
Fred Drakea6a885b2001-09-26 16:52:18 +0000119\mailheader{MIME-Version} header (always set to \code{1.0}).
Barry Warsaw5e634632001-09-26 05:23:47 +0000120\end{classdesc}
121
Barry Warsawa55d1322001-10-09 19:14:17 +0000122\begin{classdesc}{MIMEAudio}{_audiodata\optional{, _subtype\optional{,
123 _encoder\optional{, **_params}}}}
124
125A subclass of \class{MIMEBase}, the \class{MIMEAudio} class is used to
126create MIME message objects of major type \mimetype{audio}.
Barry Warsawdca93982001-10-09 19:37:51 +0000127\var{_audiodata} is a string containing the raw audio data. If this
Barry Warsawa55d1322001-10-09 19:14:17 +0000128data can be decoded by the standard Python module \refmodule{sndhdr},
129then the subtype will be automatically included in the
130\mailheader{Content-Type} header. Otherwise you can explicitly specify the
131audio subtype via the \var{_subtype} parameter. If the minor type could
132not be guessed and \var{_subtype} was not given, then \exception{TypeError}
133is raised.
134
135Optional \var{_encoder} is a callable (i.e. function) which will
136perform the actual encoding of the audio data for transport. This
137callable takes one argument, which is the \class{MIMEAudio} instance.
138It should use \method{get_payload()} and \method{set_payload()} to
139change the payload to encoded form. It should also add any
140\mailheader{Content-Transfer-Encoding} or other headers to the message
141object 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}
145constructor.
146\end{classdesc}
147
Barry Warsaw5e634632001-09-26 05:23:47 +0000148\begin{classdesc}{MIMEImage}{_imagedata\optional{, _subtype\optional{,
149 _encoder\optional{, **_params}}}}
150
151A subclass of \class{MIMEBase}, the \class{MIMEImage} class is used to
Fred Drakea6a885b2001-09-26 16:52:18 +0000152create MIME message objects of major type \mimetype{image}.
Barry Warsaw5e634632001-09-26 05:23:47 +0000153\var{_imagedata} is a string containing the raw image data. If this
154data can be decoded by the standard Python module \refmodule{imghdr},
155then the subtype will be automatically included in the
Fred Drakea6a885b2001-09-26 16:52:18 +0000156\mailheader{Content-Type} header. Otherwise you can explicitly specify the
Barry Warsaw5e634632001-09-26 05:23:47 +0000157image subtype via the \var{_subtype} parameter. If the minor type could
Fred Drakea6a885b2001-09-26 16:52:18 +0000158not be guessed and \var{_subtype} was not given, then \exception{TypeError}
Barry Warsaw5e634632001-09-26 05:23:47 +0000159is raised.
160
161Optional \var{_encoder} is a callable (i.e. function) which will
162perform the actual encoding of the image data for transport. This
163callable takes one argument, which is the \class{MIMEImage} instance.
164It should use \method{get_payload()} and \method{set_payload()} to
165change the payload to encoded form. It should also add any
Fred Drakea6a885b2001-09-26 16:52:18 +0000166\mailheader{Content-Transfer-Encoding} or other headers to the message
Barry Warsaw5e634632001-09-26 05:23:47 +0000167object 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}
171constructor.
172\end{classdesc}
173
174\begin{classdesc}{MIMEText}{_text\optional{, _subtype\optional{,
175 _charset\optional{, _encoder}}}}
Barry Warsawc5f8fe32001-09-26 22:21:52 +0000176
Barry Warsaw5e634632001-09-26 05:23:47 +0000177A subclass of \class{MIMEBase}, the \class{MIMEText} class is used to
Barry Warsawc5f8fe32001-09-26 22:21:52 +0000178create MIME objects of major type \mimetype{text}. \var{_text} is the
179string for the payload. \var{_subtype} is the minor type and defaults
180to \mimetype{plain}. \var{_charset} is the character set of the text and is
Barry Warsaw5e634632001-09-26 05:23:47 +0000181passed as a parameter to the \class{MIMEBase} constructor; it defaults
182to \code{us-ascii}. No guessing or encoding is performed on the text
183data, but a newline is appended to \var{_text} if it doesn't already
184end with a newline.
185
186The \var{_encoding} argument is as with the \class{MIMEImage} class
187constructor, except that the default encoding for \class{MIMEText}
188objects is one that doesn't actually modify the payload, but does set
Fred Drakea6a885b2001-09-26 16:52:18 +0000189the \mailheader{Content-Transfer-Encoding} header to \code{7bit} or
Barry Warsaw5e634632001-09-26 05:23:47 +0000190\code{8bit} as appropriate.
191\end{classdesc}
192
193\begin{classdesc}{MIMEMessage}{_msg\optional{, _subtype}}
194A subclass of \class{MIMEBase}, the \class{MIMEMessage} class is used to
Fred Drakea6a885b2001-09-26 16:52:18 +0000195create MIME objects of main type \mimetype{message}. \var{_msg} is used as
Barry Warsaw5e634632001-09-26 05:23:47 +0000196the payload, and must be an instance of class \class{Message} (or a
197subclass thereof), otherwise a \exception{TypeError} is raised.
198
199Optional \var{_subtype} sets the subtype of the message; it defaults
Fred Drakea6a885b2001-09-26 16:52:18 +0000200to \mimetype{rfc822}.
Barry Warsaw5e634632001-09-26 05:23:47 +0000201\end{classdesc}
202
Barry Warsawc5f8fe32001-09-26 22:21:52 +0000203\subsection{Encoders}
204\input{emailencoders}
Barry Warsaw5e634632001-09-26 05:23:47 +0000205
Barry Warsawc5f8fe32001-09-26 22:21:52 +0000206\subsection{Exception classes}
207\input{emailexc}
Barry Warsaw5e634632001-09-26 05:23:47 +0000208
Barry Warsawc5f8fe32001-09-26 22:21:52 +0000209\subsection{Miscellaneous utilities}
210\input{emailutil}
Barry Warsaw5e634632001-09-26 05:23:47 +0000211
Barry Warsawc5f8fe32001-09-26 22:21:52 +0000212\subsection{Iterators}
213\input{emailiter}
Barry Warsaw5e634632001-09-26 05:23:47 +0000214
215\subsection{Differences from \module{mimelib}}
216
217The \module{email} package was originally prototyped as a separate
Barry Warsawc5f8fe32001-09-26 22:21:52 +0000218library called
219\ulink{\module{mimelib}}{http://mimelib.sf.net/}.
220Changes have been made so that
Barry Warsaw5e634632001-09-26 05:23:47 +0000221method names are more consistent, and some methods or modules have
222either been added or removed. The semantics of some of the methods
223have also changed. For the most part, any functionality available in
Fred Drake90e68782001-09-27 20:09:39 +0000224\module{mimelib} is still available in the \refmodule{email} package,
Barry Warsaw5e634632001-09-26 05:23:47 +0000225albeit often in a different way.
226
227Here is a brief description of the differences between the
Fred Drake90e68782001-09-27 20:09:39 +0000228\module{mimelib} and the \refmodule{email} packages, along with hints on
Barry Warsaw5e634632001-09-26 05:23:47 +0000229how to port your applications.
230
231Of course, the most visible difference between the two packages is
Fred Drake90e68782001-09-27 20:09:39 +0000232that the package name has been changed to \refmodule{email}. In
Barry Warsaw5e634632001-09-26 05:23:47 +0000233addition, 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
242The \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 Warsawc5f8fe32001-09-26 22:21:52 +0000261 the key/value pairs of the parameters, split on the \character{=}
Barry Warsaw5e634632001-09-26 05:23:47 +0000262 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
285The \class{Parser} class has no differences in its public interface.
286It does have some additional smarts to recognize
Fred Drakea6a885b2001-09-26 16:52:18 +0000287\mimetype{message/delivery-status} type messages, which it represents as
Barry Warsaw5e634632001-09-26 05:23:47 +0000288a \class{Message} instance containing separate \class{Message}
289subparts for each header block in the delivery status
290notification\footnote{Delivery Status Notifications (DSN) are defined
Fred Drake90e68782001-09-27 20:09:39 +0000291in \rfc{1894}.}.
Barry Warsaw5e634632001-09-26 05:23:47 +0000292
293The \class{Generator} class has no differences in its public
294interface. There is a new class in the \refmodule{email.Generator}
295module though, called \class{DecodedGenerator} which provides most of
296the functionality previously available in the
297\method{Message.getpayloadastext()} method.
298
299The 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 Drakea6a885b2001-09-26 16:52:18 +0000318 MIME message with main type \mimetype{message}. It takes an
Barry Warsaw5e634632001-09-26 05:23:47 +0000319 optional argument \var{_subtype} which is used to set the MIME
Fred Drakea6a885b2001-09-26 16:52:18 +0000320 subtype. \var{_subtype} defaults to \mimetype{rfc822}.
Barry Warsaw5e634632001-09-26 05:23:47 +0000321\end{itemize}
322
323\module{mimelib} provided some utility functions in its
324\module{address} and \module{date} modules. All of these functions
325have been moved to the \refmodule{email.Utils} module.
326
327The \code{MsgReader} class/module has been removed. Its functionality
328is most closely supported in the \function{body_line_iterator()}
329function in the \refmodule{email.Iterators} module.
330
331\subsection{Examples}
332
Barry Warsaw2bb077f2001-11-05 17:50:53 +0000333Here are a few examples of how to use the \module{email} package to
334read, write, and send simple email messages, as well as more complex
335MIME messages.
336
337First, let's see how to create and send a simple text message:
338
339\begin{verbatim}
340# Import smtplib for the actual sending function
341import smtplib
342
343# Here are the email pacakge modules we'll need
344from email import Encoders
345from email.MIMEText import MIMEText
346
347# Open a plain text file for reading
348fp = open(textfile)
349# Create a text/plain message, using Quoted-Printable encoding for non-ASCII
350# characters.
351msg = MIMEText(fp.read(), _encoder=Encoders.encode_quopri)
352fp.close()
353
354# me == the sender's email address
355# you == the recipient's email address
356msg['Subject'] = 'The contents of \%s' \% textfile
357msg['From'] = me
358msg['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.
362s = smtplib.SMTP()
363s.connect()
364s.sendmail(me, [you], msg.as_string(0))
365s.close()
366\end{verbatim}
367
368Here's an example of how to send a MIME message containing a bunch of
369family pictures:
370
371\begin{verbatim}
372# Import smtplib for the actual sending function
373import smtplib
374
375# Here are the email pacakge modules we'll need
376from email.MIMEImage import MIMEImage
377from email.MIMEBase import MIMEBase
378
379COMMASPACE = ', '
380
381# Create the container (outer) email message.
382# me == the sender's email address
383# family = the list of all recipients' email addresses
384msg = MIMEBase('multipart', 'mixed')
385msg['Subject'] = 'Our family reunion'
386msg['From'] = me
387msg['To'] = COMMASPACE.join(family)
388msg.preamble = 'Our family reunion'
389# Guarantees the message ends in a newline
390msg.epilogue = ''
391
392# Assume we know that the image files are all in PNG format
393for 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.
402s = smtplib.SMTP()
403s.connect()
404s.sendmail(me, family, msg.as_string(unixfrom=0))
405s.close()
406\end{verbatim}
407
408Here's an example\footnote{Thanks to Matthew Dixon Cowles for the
409original inspiration and examples.} of how to send the entire contents
410of 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
417Usage: dirmail [options] from to [to ...]*
418
419Options:
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
432recipients may be given.
433
434The email is sent by forwarding to your local SMTP server, which then does the
435normal delivery process. Your local machine must be running an SMTP server.
436"""
437
438import sys
439import os
440import getopt
441import smtplib
442# For guessing MIME type based on file name extension
443import mimetypes
444
445from email import Encoders
446from email.Message import Message
447from email.MIMEAudio import MIMEAudio
448from email.MIMEBase import MIMEBase
449from email.MIMEImage import MIMEImage
450from email.MIMEText import MIMEText
451
452COMMASPACE = ', '
453
454
455def usage(code, msg=''):
456 print >> sys.stderr, __doc__
457 if msg:
458 print >> sys.stderr, msg
459 sys.exit(code)
460
461
462def 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')
483 outer['Subject'] = 'Contents of directory \%s' \% os.path.abspath(dir)
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
538if __name__ == '__main__':
539 main()
540\end{verbatim}
541
542And finally, here's an example of how to unpack a MIME message like
543the 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
550Usage: unpackmail [options] msgfile
551
552Options:
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
561msgfile is the path to the file containing the MIME message.
562"""
563
564import sys
565import os
566import getopt
567import errno
568import mimetypes
569import email
570
571
572def usage(code, msg=''):
573 print >> sys.stderr, __doc__
574 if msg:
575 print >> sys.stderr, msg
576 sys.exit(code)
577
578
579def 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'
620 filename = 'part-\%03d\%s' \% (counter, ext)
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
627if __name__ == '__main__':
628 main()
629\end{verbatim}