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 と 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
DateHeaderparser 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
datetimeinstance 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), thendatetimewill be a naivedatetime. If a specific timezone offset is found (including+0000), thendatetimewill contain an awaredatetimethat usesdatetime.timezoneto 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
decodedvalue of the header will have all encoded words decoded to unicode.idnaencoded domain names are also decoded to unicode. Thedecodedvalue is set by joining thestrvalue of the elements of thegroupsattribute with', '.A list of
AddressandGroupobjects in any combination may be used to set the value of an address header.Groupobjects whosedisplay_nameisNonewill be interpreted as single addresses, which allows an address list to be copied with groups intact by using the list obtained from thegroupsattribute 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 aValueError.
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-Nonevalues 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¶
inlineandattachmentare the only valid values in common use.
- class email.headerregistry.ContentTransferEncoding¶
Content-Transfer-Encoding ヘッダを扱います。
- class email.headerregistry.HeaderRegistry(base_class=BaseHeader, default_class=UnstructuredHeader, use_default_map=True)¶
This is the factory used by
EmailPolicyby default.HeaderRegistrybuilds 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 isTrue(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
Addresswill 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@domainportion of the address, correctly quoted for use as a bare address (the second form shown above). This attribute is not mutable.
- __str__()¶
The
strvalue 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),
Addresshandles one special case: ifusernameanddomainare both the empty string (orNone), then the string value of theAddressis<>.
- 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
Groupmay also be used to represent single addresses that are not part of a group by setting display_name toNoneand providing a list of the single address as addresses.- display_name¶
The
display_nameof the group. If it isNoneand there is exactly oneAddressinaddresses, then theGrouprepresents a single address that is not in a group.
脚注