| 1 |
.. _email-examples: |
| 2 |
|
| 3 |
:mod:`email`: Examples |
| 4 |
---------------------- |
| 5 |
|
| 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. |
| 8 |
|
| 9 |
First, let's see how to create and send a simple text message (both the |
| 10 |
text content and the addresses may contain unicode characters): |
| 11 |
|
| 12 |
.. literalinclude:: ../includes/email-simple.py |
| 13 |
|
| 14 |
|
| 15 |
Parsing :rfc:`822` headers can easily be done by the using the classes |
| 16 |
from the :mod:`~email.parser` module: |
| 17 |
|
| 18 |
.. literalinclude:: ../includes/email-headers.py |
| 19 |
|
| 20 |
|
| 21 |
Here's an example of how to send a MIME message containing a bunch of family |
| 22 |
pictures that may be residing in a directory: |
| 23 |
|
| 24 |
.. literalinclude:: ../includes/email-mime.py |
| 25 |
|
| 26 |
|
| 27 |
Here's an example of how to send the entire contents of a directory as an email |
| 28 |
message: [1]_ |
| 29 |
|
| 30 |
.. literalinclude:: ../includes/email-dir.py |
| 31 |
|
| 32 |
|
| 33 |
Here's an example of how to unpack a MIME message like the one |
| 34 |
above, into a directory of files: |
| 35 |
|
| 36 |
.. literalinclude:: ../includes/email-unpack.py |
| 37 |
|
| 38 |
|
| 39 |
Here's an example of how to create an HTML message with an alternative plain |
| 40 |
text version. To make things a bit more interesting, we include a related |
| 41 |
image in the html part, and we save a copy of what we are going to send to |
| 42 |
disk, as well as sending it. |
| 43 |
|
| 44 |
.. literalinclude:: ../includes/email-alternative.py |
| 45 |
|
| 46 |
|
| 47 |
If we were sent the message from the last example, here is one way we could |
| 48 |
process it: |
| 49 |
|
| 50 |
.. literalinclude:: ../includes/email-read-alternative.py |
| 51 |
|
| 52 |
Up to the prompt, the output from the above is: |
| 53 |
|
| 54 |
.. code-block:: none |
| 55 |
|
| 56 |
To: Penelope Pussycat <[email protected]>, Fabrette Pussycat <[email protected]> |
| 57 |
From: Pepé Le Pew <[email protected]> |
| 58 |
Subject: Pourquoi pas des asperges pour ce midi ? |
| 59 |
|
| 60 |
Salut! |
| 61 |
|
| 62 |
Cette recette [1] sera sûrement un très bon repas. |
| 63 |
|
| 64 |
|
| 65 |
.. rubric:: Footnotes |
| 66 |
|
| 67 |
.. [1] Thanks to Matthew Dixon Cowles for the original inspiration and examples. |