email.utils: 多方面のユーティリティ

ソースコード: Lib/email/utils.py


email.utils モジュールではいくつかの便利なユーティリティを提供しています:

email.utils.localtime(dt=None)

Return local time as an aware datetime object. If called without arguments, return current time. Otherwise dt argument should be a datetime instance, and it is converted to the local time zone according to the system time zone database. If dt is naive (that is, dt.tzinfo is None), it is assumed to be in local time. The isdst parameter is ignored.

バージョン 3.3 で追加.

バージョン 3.12 で非推奨、バージョン 3.14 で削除予定: The isdst parameter.

email.utils.make_msgid(idstring=None, domain=None)

Returns a string suitable for an RFC 2822-compliant Message-ID header. Optional idstring if given, is a string used to strengthen the uniqueness of the message id. Optional domain if given provides the portion of the msgid after the '@'. The default is the local hostname. It is not normally necessary to override this default, but may be useful certain cases, such as a constructing distributed system that uses a consistent domain name across multiple hosts.

バージョン 3.2 で変更: domain キーワードが追加されました。

The remaining functions are part of the legacy (Compat32) email API. There is no need to directly use these with the new API, since the parsing and formatting they provide is done automatically by the header parsing machinery of the new API.

email.utils.quote(str)

文字列 str 内のバックスラッシュをバックスラッシュ2つに置換した新しい文字列を返します。また、ダブルクォートはバックスラッシュ + ダブルクォートに置換されます。

email.utils.unquote(str)

文字列 strクォートを外した 新しい文字列を返します。str の先頭と末尾がダブルクォートだった場合、それらは取り除かれます。同様に str の先頭と末尾が角ブラケット (<、>) だった場合もそれらは取り除かれます。

email.utils.parseaddr(address)

ToCc のようなフィールドを持つアドレスをパースして、構成要素の 実名電子メールアドレス を取り出します。 パースに成功した場合、これらの情報持つタプルを返します。失敗した場合は 2 要素のタプル ('', '') を返します。

email.utils.formataddr(pair, charset='utf-8')

parseaddr() の逆で、2 要素のタプル (realname, email_address) を取って ToCc ヘッダに適した文字列を返します。タプル pair の第1要素が偽である場合、第2要素の値をそのまま返します。

任意の charset は、 realname が非 ASCII 文字を含んでいる場合にその RFC 2047 エンコーディングに使われる文字集合です。strCharset のインスタンスで、デフォルトは utf-8 です。

バージョン 3.3 で変更: charset オプションが追加されました。

email.utils.getaddresses(fieldvalues)

このメソッドは parseaddr() が返す形式の 2 要素タプルのリストを返します。 fieldvaluesMessage.get_all が返すような一連のヘッダフィールドです。 以下はメッセージの全ての受信者を得る簡単な例です:

from email.utils import getaddresses

tos = msg.get_all('to', [])
ccs = msg.get_all('cc', [])
resent_tos = msg.get_all('resent-to', [])
resent_ccs = msg.get_all('resent-cc', [])
all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)
email.utils.parsedate(date)

RFC 2822 の規則に基づいて日付の解析を試みます。 しかしながらメイラーによっては指定された形式に従っていないものがあるので、その場合 parsedate() は正しく推測しようとします。 date"Mon, 20 Nov 1995 19:12:08 -0500" のような RFC 2822 形式の日付を含む文字列です。 日付の解析に成功した場合、 parsedate() は関数 time.mktime() に直接渡せる形式の 9 要素からなるタプルを返します。 失敗した場合は None を返します。 返されるタプルの 6、7、8番目の添字は使用不可なので注意してください。

email.utils.parsedate_tz(date)

Performs the same function as parsedate(), but returns either None or a 10-tuple; the first 9 elements make up a tuple that can be passed directly to time.mktime(), and the tenth is the offset of the date's timezone from UTC (which is the official term for Greenwich Mean Time) [1]. If the input string has no timezone, the last element of the tuple returned is 0, which represents UTC. Note that indexes 6, 7, and 8 of the result tuple are not usable.

email.utils.parsedate_to_datetime(date)

The inverse of format_datetime(). Performs the same function as parsedate(), but on success returns a datetime; otherwise ValueError is raised if date contains an invalid value such as an hour greater than 23 or a timezone offset not between -24 and 24 hours. If the input date has a timezone of -0000, the datetime will be a naive datetime, and if the date is conforming to the RFCs it will represent a time in UTC but with no indication of the actual source timezone of the message the date comes from. If the input date has any other valid timezone offset, the datetime will be an aware datetime with the corresponding a timezone tzinfo.

バージョン 3.3 で追加.

email.utils.mktime_tz(tuple)

parsedate_tz() が返す 10 要素のタプルを UTC のタイムスタンプ (エポックからの秒数) に変換します。与えられた時間帯が None である場合、時間帯として現地時間 (localtime) が仮定されます。

email.utils.formatdate(timeval=None, localtime=False, usegmt=False)

日付を RFC 2822 形式の文字列で返します。例:

Fri, 09 Nov 2001 01:08:47 -0000

与えられた場合、オプションの timevaltime.gmtime()time.localtime() に渡すことの出来る浮動小数の時刻です。 それ以外の場合、現在時刻が使われます。

オプション引数 localtime はフラグです。True の場合、この関数は timeval を解析して UTC の代わりに現地のタイムゾーンに対する日付を返します。おそらく夏時間も考慮するでしょう。デフォルトは False で、UTC が使われます。

オプション引数 usegmt はフラグです。True の場合、この関数はタイムゾーンを数値の -0000 ではなく ascii 文字列 GMT として日付を出力します。これはプロトコルによっては (例えば HTTP) 必要です。これは localtimeFalse のときのみ適用されます。デフォルトは False です。

email.utils.format_datetime(dt, usegmt=False)

Like formatdate, but the input is a datetime instance. If it is a naive datetime, it is assumed to be "UTC with no information about the source timezone", and the conventional -0000 is used for the timezone. If it is an aware datetime, then the numeric timezone offset is used. If it is an aware timezone with offset zero, then usegmt may be set to True, in which case the string GMT is used instead of the numeric timezone offset. This provides a way to generate standards conformant HTTP date headers.

バージョン 3.3 で追加.

email.utils.decode_rfc2231(s)

RFC 2231 に従って文字列 s をデコードします。

email.utils.encode_rfc2231(s, charset=None, language=None)

RFC 2231 に従って s をエンコードします。オプション引数 charset および language が与えられた場合、これらは文字セット名と言語名として使われます。もしこれらのどちらも与えられていない場合、 s はそのまま返されます。 charset は与えられているが language が与えられていない場合、文字列 slanguage の空文字列を使ってエンコードされます。

email.utils.collapse_rfc2231_value(value, errors='replace', fallback_charset='us-ascii')

ヘッダのパラメータが RFC 2231 形式でエンコードされている場合、 Message.get_param は 3 要素からなるタプルを返すことがあります。ここには、そのパラメータの文字セット、言語、および値の順に格納されています。 collapse_rfc2231_value() はこのパラメータをひとつの Unicode 文字列にまとめます。オプション引数 errorsstrencode() メソッドの引数 errors に渡されます。このデフォルト値は 'replace' となっています。オプション引数 fallback_charset は、もし RFC 2231 ヘッダの使用している文字セットが Python の知っているものではなかった場合の非常用文字セットとして使われます。デフォルトでは、この値は 'us-ascii' です。

便宜上、 collapse_rfc2231_value() に渡された引数 value がタプルでない場合には、これは文字列でなければなりません。その場合にはクォートを除いた文字列を返します。

email.utils.decode_params(params)

RFC 2231 に従って引数のリストをデコードします。 params(content-type, string-value) のような形式の 2 要素タプルです。

脚注