> **Источник:** https://python-all.ru/3.2/library/email-examples.html
>
> «Документация Python на русском» – неофициальный перевод официальной документации Python: версии от 2.6 до 3.16, полнотекстовый поиск, английский оригинал рядом с переводом. Эта Markdown-версия страницы предназначена для работы с LLM: вставьте её в ChatGPT, Claude или Cursor.

---

# 18.1.11. [`email`](https://python-all.ru/3.2/library/email.html#module-email): Примеры

Вот несколько примеров использования пакета [`email`](https://python-all.ru/3.2/library/email.html#module-email) для чтения, записи и отправки простых email-сообщений, а также более сложных MIME-сообщений.

Сначала посмотрим, как создать и отправить простое текстовое сообщение:

```python
# Импорт smtplib для функции отправки
import smtplib

# Импортируются необходимые модули email.
from email.mime.text import MIMEText

# Открыть обычный текстовый файл для чтения. В этом примере предполагается, что
# текстовый файл содержит только символы ASCII.
fp = open(textfile, 'rb')
# Создать сообщение text/plain
msg = MIMEText(fp.read())
fp.close()

# me == адрес электронной почты отправителя
# you == адрес электронной почты получателя
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Отправить сообщение через собственный SMTP-сервер.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
```

Разбор заголовков RFC822 легко выполняется с помощью методов parse(filename) или parsestr(message\_as\_string) класса Parser():

```python
# Импортируются необходимые модули email.
from email.parser import Parser

#  Если заголовки электронного письма находятся в файле, раскомментируйте эту строку:
#headers = Parser().parse(open(messagefile, 'r'))

#  Или для разбора заголовков из строки используйте:
headers = Parser().parsestr('From: <user@example.com>\n'
        'To: <someone_else@example.com>\n'
        'Subject: Test message\n'
        '\n'
        'Body would go here\n')

#  Теперь к элементам заголовков можно обращаться как к словарю:
print('To: %s' % headers['to'])
print('From: %s' % headers['from'])
print('Subject: %s' % headers['subject'])
```

Вот пример отправки MIME-сообщения, содержащего много семейных фотографий, которые могут находиться в каталоге:

```python
# Импорт smtplib для функции отправки
import smtplib

# Вот модули пакета email, которые нам понадобятся
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

# Создать контейнер (внешнее) email-сообщение.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == адрес электронной почты отправителя
# family = список адресов электронной почты всех получателей
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'

# Предположим, что все файлы изображений в формате PNG.
for file in pngfiles:
    # Открыть файлы в двоичном режиме. Пусть класс MIMEImage автоматически
    # определяет конкретный тип изображения.
    fp = open(file, 'rb')
    img = MIMEImage(fp.read())
    fp.close()
    msg.attach(img)

# Отправляем email через собственный SMTP-сервер.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
```

Вот пример отправки всего содержимого каталога в виде email- сообщения: [\[1\]](https://python-all.ru/3.2/library/email-examples.html#id4)

```python
#!/usr/bin/env python3

"""Отправляем содержимое каталога как MIME-сообщение."""

import os
import sys
import smtplib
# Для определения типа MIME по расширению имени файла
import mimetypes

from optparse import OptionParser

from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

COMMASPACE = ', '

def main():
    parser = OptionParser(usage="""\
Send the contents of a directory as a MIME message.

Usage: %prog [options]

Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
""")
    parser.add_option('-d', '--directory',
                      type='string', action='store',
                      help="""Mail the contents of the specified directory,
                      otherwise use the current directory.  Only the regular
                      files in the directory are sent, and we don't recurse to
                      subdirectories.""")
    parser.add_option('-o', '--output',
                      type='string', action='store', metavar='FILE',
                      help="""Print the composed message to FILE instead of
                      sending the message to the SMTP server.""")
    parser.add_option('-s', '--sender',
                      type='string', action='store', metavar='SENDER',
                      help='The value of the From: header (required)')
    parser.add_option('-r', '--recipient',
                      type='string', action='append', metavar='RECIPIENT',
                      default=[], dest='recipients',
                      help='A To: header value (at least one required)')
    opts, args = parser.parse_args()
    if not opts.sender or not opts.recipients:
        parser.print_help()
        sys.exit(1)
    directory = opts.directory
    if not directory:
        directory = '.'
    # Создать внешнее (оборачивающее) сообщение.
    outer = MIMEMultipart()
    outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
    outer['To'] = COMMASPACE.join(opts.recipients)
    outer['From'] = opts.sender
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # Определяем тип содержимого по расширению файла. Кодировка
        # будет проигнорирована, хотя стоит проверять простые вещи, такие как
        # gzip-файлы или сжатые файлы.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # Не удалось определить тип, или файл закодирован (сжат), поэтому
            # используем общий тип 'набор битов'.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        if maintype == 'text':
            fp = open(path)
            # Примечание: нужно обработать вычисление кодировки.
            msg = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'image':
            fp = open(path, 'rb')
            msg = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(path, 'rb')
            msg = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(path, 'rb')
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(fp.read())
            fp.close()
            # Закодировать полезную нагрузку с помощью Base64.
            encoders.encode_base64(msg)
        # Установить параметр filename.
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        outer.attach(msg)
    # Теперь отправляем или сохраняем сообщение
    composed = outer.as_string()
    if opts.output:
        fp = open(opts.output, 'w')
        fp.write(composed)
        fp.close()
    else:
        s = smtplib.SMTP('localhost')
        s.sendmail(opts.sender, opts.recipients, composed)
        s.quit()

if __name__ == '__main__':
    main()
```

Вот пример распаковки MIME-сообщения вроде показанного выше в каталог с файлами:

```python
#!/usr/bin/env python3

"""Распаковываем MIME-сообщение в каталог файлов."""

import os
import sys
import email
import errno
import mimetypes

from optparse import OptionParser

def main():
    parser = OptionParser(usage="""\
Unpack a MIME message into a directory of files.

Usage: %prog [options] msgfile
""")
    parser.add_option('-d', '--directory',
                      type='string', action='store',
                      help="""Unpack the MIME message into the named
                      directory, which will be created if it doesn't already
                      exist.""")
    opts, args = parser.parse_args()
    if not opts.directory:
        parser.print_help()
        sys.exit(1)

    try:
        msgfile = args[0]
    except IndexError:
        parser.print_help()
        sys.exit(1)

    try:
        os.mkdir(opts.directory)
    except OSError as e:
        # Игнорировать ошибку существования каталога
        if e.errno != errno.EEXIST:
            raise

    fp = open(msgfile)
    msg = email.message_from_file(fp)
    fp.close()

    counter = 1
    for part in msg.walk():
        # multipart/* – это просто контейнеры
        if part.get_content_maintype() == 'multipart':
            continue
        # Приложениям следует тщательно проверять имя файла, чтобы
        # email-сообщение не могло перезаписать важные файлы
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Использовать универсальное расширение для набора битов.
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1
        fp = open(os.path.join(opts.directory, filename), 'wb')
        fp.write(part.get_payload(decode=True))
        fp.close()

if __name__ == '__main__':
    main()
```

Here’s an example of how to create an HTML message with an alternative plain text version: [\[2\]](https://python-all.ru/3.2/library/email-examples.html#id5)

```python
#!/usr/bin/env python3

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == мой адрес электронной почты.
# you == адрес электронной почты получателя.
me = "my@email.com"
you = "your@email.com"

# Создать контейнер сообщения – правильный тип MIME – multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Создать тело сообщения (версии в виде простого текста и HTML).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="http://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""

# Записать MIME-типы обеих частей – text/plain и text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Прикрепить части к контейнеру сообщения.
# Согласно RFC 2046, последняя часть многокомпонентного сообщения, в данном случае
# HTML-сообщение, является наилучшим и предпочтительным.
msg.attach(part1)
msg.attach(part2)

# Отправка сообщения через локальный SMTP-сервер.
s = smtplib.SMTP('localhost')
# Функция sendmail принимает 3 аргумента: адрес отправителя, адрес получателя
# и сообщение для отправки – здесь оно отправляется в виде одной строки.
s.sendmail(me, you, msg.as_string())
s.quit()
```

Сноски

| [\[1\]](https://python-all.ru/3.2/library/email-examples.html#id2) | Спасибо Matthew Dixon Cowles за оригинальную идею и примеры. |
| --- | --- |

| [\[2\]](https://python-all.ru/3.2/library/email-examples.html#id3) | Автор: Martin Matejek. |
| --- | --- |
