"email.headerregistry": Custom Header Objects
*********************************************

**ソースコード:** Lib/email/headerregistry.py

======================================================================

Added in version 3.6: [1]

ヘッダーは "str" のカスタマイズされたサブクラスで表現されます。 与えら
れたヘッダーを表現するために使用される特定のクラスは、ヘッダーが作成さ
れるときに有効な "policy" の "header_factory" で決定されます。 このセ
クションでは、email ライブラリが **RFC 5322** に準拠したメールメッセー
ジを扱うために実装している、特定の "header_factory" について説明します
。このヘッダーは、様々なヘッダータイプに対してカスタマイズされたヘッダ
ーオブジェクトを提供するだけでなく、アプリケーションが独自のカスタムヘ
ッダータイプを追加できるような拡張メカニズムも備えています。

"EmailPolicy" から派生したポリシーオブジェクトのいずれかを使用する場合
、すべてのヘッダーは "HeaderRegistry" によって生成され、最終的な基底ク
ラスとして "BaseHeader" を有します。 各ヘッダクラスには、ヘッダの種類
によって決まる追加のベースクラスがあります。 例えば、多くのヘッダーは
"UnstructuredHeader" というクラスをもうひとつの基底クラスとして持って
います。 ヘッダーに特化した第二のクラスは、ヘッダーの名前によって決定
され、 "HeaderRegistry" に格納されたルックアップテーブルを使用します。
これらすべては、典型的なアプリケーションプログラムに対しては透過的に管
理されますが、より複雑なアプリケーションで使用するためにデフォルトの動
作を変更するためのインタフェースが提供されています。

以下のセクションでは、まずヘッダーの基本クラスとその属性を説明し、次に
"HeaderRegistry" の動作を変更するための API、そして最後に構造化ヘッダ
ーからパースされたデータを表現するためのサポートクラスについて説明しま
す。

class email.headerregistry.BaseHeader(name, value)

   *name* and *value* are passed to "BaseHeader" from the
   "header_factory" call.  The string value of any header object is
   the *value* fully decoded to a string.

   基底クラスは以下の読み出し専用属性を定義しています:

   name

      ヘッダーの名前(フィールドの':'の前の部分)。これは
      "header_factory" の *name* の呼び出しで渡された値と全く同じです;
      つまり、大文字・小文字が保持されます。

   defects

      パース中に見つかったRFCのコンプライアンス問題を報告する
      "HeaderDefect" インスタンスのタプルです。 email パッケージはコン
      プライアンスに関する問題を完全に検出するように努めています。 報
      告されるかもしれない欠陥の種類の議論については、 "errors" モジュ
      ールを参照してください。

   max_count

      このタイプのヘッダーで、同じ "name" を持つことができる最大数。
      値として "None" を指定すると、無制限になります。 この属性の
      "BaseHeader" の値は "None" です; 特殊な header クラスでは、必要
      に応じてこの値をオーバーライドすることが期待されます。

   "BaseHeader" は以下のメソッドも提供します。このメソッドはemail ライ
   ブラリのコードから呼び出され、一般にアプリケーションプログラムから
   は呼び出されません：

   fold(*, policy)

      ヘッダを *policy* に従って正しく折りたたむために必要な "linesep"
      文字を含む文字列を返します。 ヘッダには任意のバイナリデータを含
      めることができないため、 "cte_type" が "8bit" の場合は "7bit" と
      同じように扱われます。 もし "utf8" が "False" であれば、非ASCII
      データは **RFC 2047** でエンコードされます。

   "BaseHeader" 自身はヘッダーオブジェクトを生成するために使用すること
   はできません。このクラスは、それぞれの特殊化ヘッダーがヘッダーオブ
   ジェクトを生成するために協力するプロトコルを定義しています。 具体的
   には、 "BaseHeader" は "parse" という名前の "classmethod()" を特殊
   化されたクラスが提供することを要求しています。このメソッドは以下の
   ように呼び出されます:

      parse(string, kwds)

   "kwds" is a dictionary containing one pre-initialized key,
   "defects". "defects" is an empty list.  The parse method should
   append any detected defects to this list.  On return, the "kwds"
   dictionary *must* contain values for at least the keys "decoded",
   "defects" and "parse_tree". "decoded" should be the string value
   for the header (that is, the header value fully decoded to a
   string). "parse_tree" is set to the parse tree obtained from
   parsing the header. The parse method should assume that *string*
   may contain content-transfer-encoded parts, but should correctly
   handle all valid Unicode characters as well so that it can parse
   un-encoded header values.

   その後、 "BaseHeader" の "__new__" がヘッダのインスタンスを生成し、
   "init" メソッドを呼び出します。 特殊クラスは、 "BaseHeader" が提供
   しない属性を設定したい場合にのみ "init" メソッドを提供する必要があ
   ります。 このような``init`` メソッドは以下のようなものです：

      def init(self, /, *args, **kw):
          self._myattr = kw.pop('myattr')
          super().init(*args, **kw)

   つまり、特殊クラスが "kwds" の辞書に追加したものはすべて削除して処
   理し、 "kw``の残りの内容 (と ``args") は``BaseHeader`` の``init``
   メソッドに渡す必要があるのです。

class email.headerregistry.UnstructuredHeader

   "unstructured" ヘッダは **RFC 5322** におけるデフォルトのヘッダのタ
   イプです。指定された構文を持たないすべてのヘッダは、unstructuredと
   して扱われます。 構造化されていないヘッダの典型的な例は *Subject*
   ヘッダです。

   In **RFC 5322**, an unstructured header is a run of arbitrary text
   in the ASCII character set.  **RFC 2047**, however, has an **RFC
   5322** compatible mechanism for encoding non-ASCII text as ASCII
   characters within a header value.  When a *value* containing
   encoded words is passed to the constructor, the
   "UnstructuredHeader" parser converts such encoded words into a
   string, following the **RFC 2047** rules for unstructured text.
   The parser uses heuristics to attempt to decode certain non-
   compliant encoded words.  Defects are registered in such cases, as
   well as defects for issues such as invalid characters within the
   encoded words or the non-encoded text.

   このヘッダ型には追加の属性はありません。

class email.headerregistry.DateHeader

   **RFC 5322** specifies a very specific format for dates within
   email headers. The "DateHeader" parser recognizes that date format,
   as well as recognizing a number of variant forms that are sometimes
   found "in the wild".

   このヘッダ型は以下の属性も提供しています:

   datetime

      If the header value can be recognized as a valid date of one
      form or another, this attribute will contain a "datetime"
      instance representing that date.  If the timezone of the input
      date is specified as "-0000" (indicating it is in UTC but
      contains no information about the source timezone), then
      "datetime" will be a naive "datetime".  If a specific timezone
      offset is found (including "+0000"), then "datetime" will
      contain an aware "datetime" that uses "datetime.timezone" to
      record the timezone offset.

   ヘッダーの "decoded" 値は、 "datetime" を **RFC 5322** のルールに従
   ってフォーマットすることで決定されます。

      email.utils.format_datetime(self.datetime)

   "DateHeader" を作成する際に、 *value* は "datetime" インスタンスで
   ある可能性があります。 これは、例えば、次のようなコードは有効であり
   、期待通りの動作をすることを意味します:

      msg['Date'] = datetime(2011, 7, 15, 21)

   これは単純な "datetime" であるため、UTC タイムスタンプとして解釈さ
   れ、結果として "-0000" というタイムゾーンを持つ値になります。 もっ
   と便利なのは "utils" モジュールの "localtime()" 関数を使用すること
   です:

      msg['Date'] = utils.localtime()

   この例では、現在のタイムゾーンオフセットを使用して、日付ヘッダーを
   現在の時刻と日付に設定します。

class email.headerregistry.AddressHeader

   アドレスヘッダは最も複雑な構造のヘッダタイプの1つです。
   "AddressHeader" クラスは、あらゆるアドレスヘッダに対する汎用的なイ
   ンターフェースを提供します。

   このヘッダ型は以下の属性も提供しています:

   groups

      ヘッダー値に含まれるアドレスとグループをエンコードした "Group"
      オブジェクトのタプルです。 グループに属さないアドレスは、このリ
      ストでは "display_name" が "None" であるシングルアドレスの
      "Groups" として表現されます。

   addresses

      ヘッダー値に含まれる全ての個別アドレスをエンコードした "Address"
      オブジェクトのタプルです。 ヘッダ値にグループが含まれている場合
      、そのグループに含まれる個々のアドレスは、ヘッダ値でグループが出
      現した時点でリストに含まれます (つまり、アドレスのリストは一次元
      のリストに「フラット化」されます)。

   The "decoded" value of the header will have all encoded words
   decoded to a string.  "idna" encoded domain names are also decoded
   to a string.  The "decoded" value is set by joining the "str" value
   of the elements of the "groups" attribute with "', '".

   A list of "Address" and "Group" objects in any combination may be
   used to set the value of an address header.  "Group" objects whose
   "display_name" is "None" will be interpreted as single addresses,
   which allows an address list to be copied with groups intact by
   using the list obtained from the "groups" attribute of the source
   header.

class email.headerregistry.SingleAddressHeader

   追加の属性を 1 つ持つ、"AddressHeader" の派生クラスです:

   address

      The single address encoded by the header value.  If the header
      value actually contains more than one address (which would be a
      violation of the RFC under the default "policy"), accessing this
      attribute will result in a "ValueError".

Many of the above classes also have a "Unique" variant (for example,
"UniqueUnstructuredHeader").  The only difference is that in the
"Unique" variant, "max_count" is set to 1.

class email.headerregistry.MIMEVersionHeader

   There is really only one valid value for the *MIME-Version* header,
   and that is "1.0".  For future proofing, this header class supports
   other valid version numbers.  If a version number has a valid value
   per **RFC 2045**, then the header object will have non-"None"
   values for the following attributes:

   version

      バージョン番号 (文字列)、空白やコメントは除かれます。

   major

      メジャーバージョン番号 (整数)

   minor

      マイナーバージョン番号 (整数)

class email.headerregistry.ParameterizedMIMEHeader

   MIME headers all start with the prefix 'Content-'.  Each specific
   header has a certain value, described under the class for that
   header.  Some can also take a list of supplemental parameters,
   which have a common format. This class serves as a base for all the
   MIME headers that take parameters.

   params

      A dictionary mapping parameter names to parameter values.

class email.headerregistry.ContentTypeHeader

   *Content-Type* ヘッダを扱う "ParameterizedMIMEHeader" クラスです。

   content_type

      The content type string, in the form "maintype/subtype".

   maintype

   subtype

class email.headerregistry.ContentDispositionHeader

   *Content-Disposition* ヘッダを扱う "ParameterizedMIMEHeader" クラス
   です。

   content_disposition

      "inline" and "attachment" are the only valid values in common
      use.

class email.headerregistry.ContentTransferEncodingHeader

   *Content-Transfer-Encoding* ヘッダを扱います。

   cte

      有効な値は "7bit"、"8bit"、"base64"、"quoted-printable" です。詳
      細については **RFC 2045** を参照してください。

class email.headerregistry.HeaderRegistry(base_class=BaseHeader, default_class=UnstructuredHeader, use_default_map=True)

   This is the factory used by "EmailPolicy" by default.
   "HeaderRegistry" builds the class used to create a header instance
   dynamically, using *base_class* and a specialized class retrieved
   from a registry that it holds.  When a given header name does not
   appear in the registry, the class specified by *default_class* is
   used as the specialized class.  When *use_default_map* is "True"
   (the default), the standard mapping of header names to classes is
   copied in to the registry during initialization.  *base_class* is
   always the last class in the generated class's "__bases__" list.

   デフォルトのマッピング:

      subject:
         UniqueUnstructuredHeader

      date:
         UniqueDateHeader

      resent-date:
         DateHeader

      orig-date:
         UniqueDateHeader

      sender:
         UniqueSingleAddressHeader

      resent-sender:
         SingleAddressHeader

      to:
         UniqueAddressHeader

      resent-to:
         AddressHeader

      cc:
         UniqueAddressHeader

      resent-cc:
         AddressHeader

      bcc:
         UniqueAddressHeader

      resent-bcc:
         AddressHeader

      from:
         UniqueAddressHeader

      resent-from:
         AddressHeader

      reply-to:
         UniqueAddressHeader

      mime-version:
         MIMEVersionHeader

      content-type:
         ContentTypeHeader

      content-disposition:
         ContentDispositionHeader

      content-transfer-encoding:
         ContentTransferEncodingHeader

      message-id:
         MessageIDHeader

   "HeaderRegistry" には以下のメソッドがあります:

   map_to_type(self, name, cls)

      *name* is the name of the header to be mapped.  It will be
      converted to lower case in the registry.  *cls* is the
      specialized class to be used, along with *base_class*, to create
      the class used to instantiate headers that match *name*.

   __getitem__(name)

      Construct and return a class to handle creating a *name* header.

   __call__(name, value)

      Retrieves the specialized header associated with *name* from the
      registry (using *default_class* if *name* does not appear in the
      registry) and composes it with *base_class* to produce a class,
      calls the constructed class's constructor, passing it the same
      argument list, and finally returns the class instance created
      thereby.

The following classes are the classes used to represent data parsed
from structured headers and can, in general, be used by an application
program to construct structured values to assign to specific headers.

class email.headerregistry.Address(display_name='', username='', domain='', addr_spec=None)

   このクラスは電子メールのアドレスを表すのに使われます。アドレスの一
   般的な形式は:

      [display_name] <username@domain>

   もしくは:

      username@domain

   where each part must conform to specific syntax rules spelled out
   in **RFC 5322**.

   As a convenience *addr_spec* can be specified instead of *username*
   and *domain*, in which case *username* and *domain* will be parsed
   from the *addr_spec*.  An *addr_spec* must be a properly RFC quoted
   string; if it is not "Address" will raise an error.  Unicode
   characters are allowed and will be property encoded when
   serialized.  However, per the RFCs, Unicode is *not* allowed in the
   username portion of the address.

   display_name

      The display name portion of the address, if any, with all
      quoting removed.  If the address does not have a display name,
      this attribute will be an empty string.

   username

      アドレスの "username" 部分、クォートは取り除かれます。

   domain

      アドレスの "domain" 部分。

   addr_spec

      The "username@domain" portion of the address, correctly quoted
      for use as a bare address (the second form shown above).  This
      attribute is not mutable.

   __str__()

      The "str" value of the object is the address quoted according to
      **RFC 5322** rules, but with no Content Transfer Encoding of any
      non-ASCII characters.

   To support SMTP (**RFC 5321**), "Address" handles one special case:
   if "username" and "domain" are both the empty string (or "None"),
   then the string value of the "Address" is "<>".

class email.headerregistry.Group(display_name=None, addresses=None)

   このクラスはアドレスグループを表すのに使われます。アドレスグループ
   の一般的な形式は:

      display_name: [address-list];

   As a convenience for processing lists of addresses that consist of
   a mixture of groups and single addresses, a "Group" may also be
   used to represent single addresses that are not part of a group by
   setting *display_name* to "None" and providing a list of the single
   address as *addresses*.

   display_name

      The "display_name" of the group.  If it is "None" and there is
      exactly one "Address" in "addresses", then the "Group"
      represents a single address that is not in a group.

   addresses

      A possibly empty tuple of "Address" objects representing the
      addresses in the group.

   __str__()

      The "str" value of a "Group" is formatted according to **RFC
      5322**, but with no Content Transfer Encoding of any non-ASCII
      characters.  If "display_name" is none and there is a single
      "Address" in the "addresses" list, the "str" value will be the
      same as the "str" of that single "Address".

-[ 脚注 ]-

[1] Originally added in 3.3 as a *provisional module*
