# `email` --- An email and MIME handling package

Kode sumber: Lib/email/__init__.py

The `email` package is a library for managing email messages. It is specifically not designed to do any sending of email messages to SMTP ( RFC 2821), NNTP, or other servers; those are functions of modules such as `smtplib`. The `email` package attempts to be as RFC-compliant as possible, supporting RFC 5322 and RFC 6532, as well as such MIME-related RFCs as RFC 2045, RFC 2046, RFC 2047, RFC 2183, and RFC 2231.

Struktur keseluruhan paket email dapat dibagi menjadi tiga komponen utama, ditambah komponen keempat yang mengontrol perilaku komponen lainnya.

Komponen utama dari paket tersebut adalah "model objek" yang mewakili pesan email. Aplikasi berinteraksi dengan paket terutama melalui antarmuka model objek yang ditentukan dalam sub-modul `message`. Aplikasi dapat menggunakan API ini untuk mengajukan pertanyaan tentang email yang sudah ada, membuat email baru, atau untuk menambah atau menghapus subkomponen email yang menggunakan antarmuka model objek yang sama. Artinya, mengikuti sifat pesan email dan subkomponen MIME-nya, model objek email adalah struktur pohon objek yang semuanya menyediakan API `EmailMessage`.

Dua komponen utama lainnya dari paket tersebut adalah `parser` dan `generator`. Parser mengambil versi serial dari pesan email (aliran byte) dan mengubahnya menjadi pohon objek `EmailMessage`. Generator mengambil `EmailMessage` dan mengubahnya kembali menjadi aliran byte serial. (Pengurai dan generator juga menangani aliran karakter teks, tetapi penggunaan ini tidak disarankan karena terlalu mudah untuk berakhir dengan pesan yang tidak valid dalam satu atau lain cara.)

Komponen kontrolnya adalah modul `policy`. Setiap `EmailMessage`, setiap `generator`, dan setiap `parser` memiliki objek terkait `policy` yang mengontrol perilakunya. Biasanya aplikasi hanya perlu menetapkan kebijakan ketika `EmailMessage` dibuat, baik dengan langsung membuat instance `EmailMessage` untuk membuat email baru, atau dengan mengurai aliran input menggunakan `parser`. Namun kebijakan tersebut dapat diubah jika pesan diserialkan menggunakan `generator`. Hal ini memungkinkan, misalnya, pesan email umum diurai dari disk, tetapi untuk membuat serialnya menggunakan pengaturan SMTP standar saat mengirimnya ke server email.

The email package does its best to hide the details of the various governing RFCs from the application. Conceptually the application should be able to treat the email message as a structured tree of unicode text and binary attachments, without having to worry about how these are represented when serialized. In practice, however, it is often necessary to be aware of at least some of the rules governing MIME messages and their structure, specifically the names and nature of the MIME "content types" and how they identify multipart documents. For the most part this knowledge should only be required for more complex applications, and even then it should only be the high level structure in question, and not the details of how those structures are represented. Since MIME content types are used widely in modern internet software (not just email), this will be a familiar concept to many programmers.

The following sections describe the functionality of the `email` package. We start with the `message` object model, which is the primary interface an application will use, and follow that with the `parser` and `generator` components. Then we cover the `policy` controls, which completes the treatment of the main components of the library.

The next three sections cover the exceptions the package may raise and the defects (non-compliance with the RFCs) that the `parser` may detect. Then we cover the `headerregistry` and the `contentmanager` sub-components, which provide tools for doing more detailed manipulation of headers and payloads, respectively. Both of these components contain features relevant to consuming and producing non-trivial messages, but also document their extensibility APIs, which will be of interest to advanced applications.

Following those is a set of examples of using the fundamental parts of the APIs covered in the preceding sections.

The foregoing represent the modern (unicode friendly) API of the email package. The remaining sections, starting with the `Message` class, cover the legacy `compat32` API that deals much more directly with the details of how email messages are represented. The `compat32` API does not hide the details of the RFCs from the application, but for applications that need to operate at that level, they can be useful tools. This documentation is also relevant for applications that are still using the `compat32` API for backward compatibility reasons.

Berubah pada versi 3.6: Docs reorganized and rewritten to promote the new `EmailMessage`/`EmailPolicy` API.

Contents of the `email` package documentation:

- `email.message`: Representing an email message
  - `EmailMessage`
    - `as_string()`
    - `__str__()`
    - `as_bytes()`
    - `__bytes__()`
    - `is_multipart()`
    - `set_unixfrom()`
    - `get_unixfrom()`
    - `__len__()`
    - `__contains__()`
    - `__getitem__()`
    - `__setitem__()`
    - `__delitem__()`
    - `keys()`
    - `values()`
    - `items()`
    - `get()`
    - `get_all()`
    - `add_header()`
    - `replace_header()`
    - `get_content_type()`
    - `get_content_maintype()`
    - `get_content_subtype()`
    - `get_default_type()`
    - `set_default_type()`
    - `set_param()`
    - `del_param()`
    - `get_filename()`
    - `get_boundary()`
    - `set_boundary()`
    - `get_content_charset()`
    - `get_charsets()`
    - `is_attachment()`
    - `get_content_disposition()`
    - `walk()`
    - `get_body()`
    - `iter_attachments()`
    - `iter_parts()`
    - `get_content()`
    - `set_content()`
    - `make_related()`
    - `make_alternative()`
    - `make_mixed()`
    - `add_related()`
    - `add_alternative()`
    - `add_attachment()`
    - `clear()`
    - `clear_content()`
    - `preamble`
    - `epilogue`
    - `defects`
  - `MIMEPart`
- `email.parser`: Parsing email messages
  - FeedParser API
    - `BytesFeedParser`
      - `feed()`
      - `close()`
    - `FeedParser`
  - Parser API
    - `BytesParser`
      - `parse()`
      - `parsebytes()`
    - `BytesHeaderParser`
    - `Parser`
      - `parse()`
      - `parsestr()`
    - `HeaderParser`
    - `message_from_bytes()`
    - `message_from_binary_file()`
    - `message_from_string()`
    - `message_from_file()`
  - Additional notes
- `email.generator`: Generating MIME documents
  - `BytesGenerator`
    - `flatten()`
    - `clone()`
    - `write()`
  - `Generator`
    - `flatten()`
    - `clone()`
    - `write()`
  - `DecodedGenerator`
- `email.policy`: Policy Objects
  - `Policy`
    - `max_line_length`
    - `linesep`
    - `cte_type`
    - `raise_on_defect`
    - `mangle_from_`
    - `message_factory`
    - `verify_generated_headers`
    - `clone()`
    - `handle_defect()`
    - `register_defect()`
    - `header_max_count()`
    - `header_source_parse()`
    - `header_store_parse()`
    - `header_fetch_parse()`
    - `fold()`
    - `fold_binary()`
  - `EmailPolicy`
    - `utf8`
    - `refold_source`
    - `header_factory`
    - `content_manager`
    - `header_max_count()`
    - `header_source_parse()`
    - `header_store_parse()`
    - `header_fetch_parse()`
    - `fold()`
    - `fold_binary()`
  - `default`
  - `SMTP`
  - `SMTPUTF8`
  - `HTTP`
  - `strict`
  - `Compat32`
    - `mangle_from_`
    - `header_source_parse()`
    - `header_store_parse()`
    - `header_fetch_parse()`
    - `fold()`
    - `fold_binary()`
  - `compat32`
- `email.errors`: Exception and Defect classes
  - `MessageError`
  - `MessageParseError`
  - `HeaderParseError`
  - `BoundaryError`
  - `MultipartConversionError`
  - `HeaderWriteError`
  - `MessageDefect`
  - `HeaderDefect`
- `email.headerregistry`: Custom Header Objects
  - `BaseHeader`
    - `name`
    - `defects`
    - `max_count`
    - `fold()`
  - `UnstructuredHeader`
  - `DateHeader`
    - `datetime`
  - `AddressHeader`
    - `groups`
    - `addresses`
  - `SingleAddressHeader`
    - `address`
  - `MIMEVersionHeader`
    - `version`
    - `major`
    - `minor`
  - `ParameterizedMIMEHeader`
    - `params`
  - `ContentTypeHeader`
    - `content_type`
    - `maintype`
    - `subtype`
  - `ContentDispositionHeader`
    - `content_disposition`
  - `ContentTransferEncoding`
    - `cte`
  - `HeaderRegistry`
    - `map_to_type()`
    - `__getitem__()`
    - `__call__()`
  - `Address`
    - `display_name`
    - `username`
    - `domain`
    - `addr_spec`
    - `__str__()`
  - `Group`
    - `display_name`
    - `addresses`
    - `__str__()`
- `email.contentmanager`: Managing MIME Content
  - `ContentManager`
    - `get_content()`
    - `set_content()`
    - `add_get_handler()`
    - `add_set_handler()`
  - Content Manager Instances
    - `raw_data_manager`
      - `get_content()`
      - `set_content()`
- `email`: Examples

Legacy API:

- `email.message.Message`: Representing an email message using the `compat32` API
  - `Message`
    - `as_string()`
    - `__str__()`
    - `as_bytes()`
    - `__bytes__()`
    - `is_multipart()`
    - `set_unixfrom()`
    - `get_unixfrom()`
    - `attach()`
    - `get_payload()`
    - `set_payload()`
    - `set_charset()`
    - `get_charset()`
    - `__len__()`
    - `__contains__()`
    - `__getitem__()`
    - `__setitem__()`
    - `__delitem__()`
    - `keys()`
    - `values()`
    - `items()`
    - `get()`
    - `get_all()`
    - `add_header()`
    - `replace_header()`
    - `get_content_type()`
    - `get_content_maintype()`
    - `get_content_subtype()`
    - `get_default_type()`
    - `set_default_type()`
    - `get_params()`
    - `get_param()`
    - `set_param()`
    - `del_param()`
    - `set_type()`
    - `get_filename()`
    - `get_boundary()`
    - `set_boundary()`
    - `get_content_charset()`
    - `get_charsets()`
    - `get_content_disposition()`
    - `walk()`
    - `preamble`
    - `epilogue`
    - `defects`
- `email.mime`: Creating email and MIME objects from scratch
  - `MIMEBase`
  - `MIMENonMultipart`
  - `MIMEMultipart`
  - `MIMEApplication`
  - `MIMEAudio`
  - `MIMEImage`
  - `MIMEMessage`
  - `MIMEText`
- `email.header`: Internationalized headers
  - `Header`
    - `append()`
    - `encode()`
    - `__str__()`
    - `__eq__()`
    - `__ne__()`
  - `decode_header()`
  - `make_header()`
- `email.charset`: Representing character sets
  - `Charset`
    - `input_charset`
    - `header_encoding`
    - `body_encoding`
    - `output_charset`
    - `input_codec`
    - `output_codec`
    - `get_body_encoding()`
    - `get_output_charset()`
    - `header_encode()`
    - `header_encode_lines()`
    - `body_encode()`
    - `__str__()`
    - `__eq__()`
    - `__ne__()`
  - `add_charset()`
  - `add_alias()`
  - `add_codec()`
- `email.encoders`: Encoders
  - `encode_quopri()`
  - `encode_base64()`
  - `encode_7or8bit()`
  - `encode_noop()`
- `email.utils`: Miscellaneous utilities
  - `localtime()`
  - `make_msgid()`
  - `quote()`
  - `unquote()`
  - `parseaddr()`
  - `formataddr()`
  - `getaddresses()`
  - `parsedate()`
  - `parsedate_tz()`
  - `parsedate_to_datetime()`
  - `mktime_tz()`
  - `formatdate()`
  - `format_datetime()`
  - `decode_rfc2231()`
  - `encode_rfc2231()`
  - `collapse_rfc2231_value()`
  - `decode_params()`
- `email.iterators`: Iterators
  - `body_line_iterator()`
  - `typed_subpart_iterator()`
  - `_structure()`

Lihat juga

Module `smtplib`

  SMTP (Simple Mail Transport Protocol) client

Module `poplib`

  POP (Post Office Protocol) client

Module `imaplib`

  IMAP (Internet Message Access Protocol) client

Module `mailbox`

  Tools for creating, reading, and managing collections of messages on disk using a variety standard formats.