6
Here are a few examples of how to use the :mod:`email` package to read, write,
7
and send simple email messages, as well as more complex MIME messages.
9
First, let's see how to create and send a simple text message:
11
.. literalinclude:: ../includes/email-simple.py
14
And parsing RFC822 headers can easily be done by the parse(filename) or
15
parsestr(message_as_string) methods of the Parser() class:
17
.. literalinclude:: ../includes/email-headers.py
20
Here's an example of how to send a MIME message containing a bunch of family
21
pictures that may be residing in a directory:
23
.. literalinclude:: ../includes/email-mime.py
26
Here's an example of how to send the entire contents of a directory as an email
29
.. literalinclude:: ../includes/email-dir.py
32
Here's an example of how to unpack a MIME message like the one
33
above, into a directory of files:
35
.. literalinclude:: ../includes/email-unpack.py
37
Here's an example of how to create an HTML message with an alternative plain
40
.. literalinclude:: ../includes/email-alternative.py
43
.. _email-contentmanager-api-examples:
45
Examples using the Provisional API
46
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
47
Here is a reworking of the last example using the provisional API. To make
48
things a bit more interesting, we include a related image in the html part, and
49
we save a copy of what we are going to send to disk, as well as sending it.
51
This example also shows how easy it is to include non-ASCII, and simplifies the
52
sending of the message using the :meth:`.send_message` method of the
53
:mod:`smtplib` module.
55
.. literalinclude:: ../includes/email-alternative-new-api.py
57
If we were instead sent the message from the last example, here is one
58
way we could process it:
60
.. literalinclude:: ../includes/email-read-alternative-new-api.py
62
Up to the prompt, the output from the above is::
64
To: Penelope Pussycat <"penelope@example.com">, Fabrette Pussycat <"fabrette@example.com">
65
From: Pepé Le Pew <pepe@example.com>
66
Subject: Ayons asperges pour le déjeuner
70
Cela ressemble à un excellent recipie[1] déjeuner.
75
.. [1] Thanks to Matthew Dixon Cowles for the original inspiration and examples.
76
.. [2] Contributed by Martin Matejek.