"email.headerregistry": カスタムヘッダーオブジェクト
****************************************************

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

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

バージョン 3.6 で追加: [1]

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

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

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

class email.headerregistry.BaseHeader(name, value)

   *name* と *value* は "header_factory" 呼び出しから "BaseHeader" に
   渡されます。 どのヘッダーオブジェクトの文字列値も、完全にユニコード
   にデコードされた *value* です。

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

   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" は、初期化されたキー "defects" を含む辞書です。"defects" は
   空のリストです。 解析メソッドは、検出された不具合をこのリストに追加
   するべきです。 returnの際には、 "kwds" 辞書に少なくとも "decoded"
   と``defects`` のキーを含む必要があります。 "decoded" はヘッダの文字
   列値 (つまり、ヘッダを Unicode に完全にデコードした値) でなければな
   りません。 parseメソッドは、 *string* がcontent-transfer-encodedな
   部分を含む可能性があると仮定すべきですが、エンコードされていないヘ
   ッダ値をパースできるように、すべての有効なUnicode文字も正しく処理す
   る必要があります。

   その後、 "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*
   ヘッダです。

   **RFC 5322** では、非構造化ヘッダは ASCII 文字セットの任意のテキス
   トの集まりです。しかし、 **RFC 2047** にはヘッダ値の中で非 ASCII テ
   キストを ASCII 文字としてエンコードするための **RFC 5322** と互換性
   のあるメカニズムが備わっています。 エンコードされた単語を含む
   *value* がコンストラクタに渡されると、 "UnstructuredHeader" パーサ
   は非構造化テキストに対する **RFC 2047** 規則に従って、エンコードさ
   れた単語を unicode に変換します。 パーサは特定の非適合なエンコード
   された単語のデコードを試みるためにヒューリスティックを使用します。
   このような場合、欠陥が登録されます。また、エンコードされた単語やエ
   ンコードされていないテキスト内の無効な文字などの問題に対しても欠陥
   が登録されます。

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

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 unicode.  "idna" encoded domain names are also decoded
   to unicode.  The "decoded" value is set by "join"ing 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.ContentTransferEncoding

   *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*
