email.utils:雜項工具

原始碼:Lib/email/utils.py


There are a couple of useful utilities provided in theemail.utilsmodule:

email.utils.localtime(dt=None)

Return local time as an aware datetime object. If called withoutarguments, return current time. Otherwisedt argument should be adatetime instance, and it is converted to the local timezone according to the system time zone database. Ifdt is naive (thatis,dt.tzinfo isNone), it is assumed to be in local time. Theisdst parameter is ignored.

在 3.3 版被加入.

Deprecated since version 3.12, will be removed in version 3.14:Theisdst parameter.

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

Returns a string suitable for anRFC 2822-compliantMessage-ID header. Optionalidstring if given, is a stringused to strengthen the uniqueness of the message id. Optionaldomain ifgiven provides the portion of the msgid after the '@'. The default is thelocal hostname. It is not normally necessary to override this default, butmay be useful certain cases, such as a constructing distributed system thatuses a consistent domain name across multiple hosts.

在 3.2 版的變更:新增domain 關鍵字。

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

email.utils.quote(str)

Return a new string with backslashes instr replaced by two backslashes, anddouble quotes replaced by backslash-double quote.

email.utils.unquote(str)

Return a new string which is anunquoted version ofstr. Ifstr ends andbegins with double quotes, they are stripped off. Likewise ifstr ends andbegins with angle brackets, they are stripped off.

email.utils.parseaddr(address,*,strict=True)

Parse address -- which should be the value of some address-containing field suchasTo orCc -- into its constituentrealname andemail address parts. Returns a tuple of that information, unless the parsefails, in which case a 2-tuple of('','') is returned.

Ifstrict is true, use a strict parser which rejects malformed inputs.

在 3.13 版的變更:Addstrict optional parameter and reject malformed inputs by default.

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

The inverse ofparseaddr(), this takes a 2-tuple of the form(realname,email_address) and returns the string value suitable for aTo orCc header. If the first element ofpair is false, then thesecond element is returned unmodified.

Optionalcharset is the character set that will be used in theRFC 2047encoding of therealname if therealname contains non-ASCIIcharacters. Can be an instance ofstr or aCharset. Defaults toutf-8.

在 3.3 版的變更:新增charset 選項。

email.utils.getaddresses(fieldvalues,*,strict=True)

This method returns a list of 2-tuples of the form returned byparseaddr().fieldvalues is a sequence of header field values as might be returned byMessage.get_all.

Ifstrict is true, use a strict parser which rejects malformed inputs.

Here's a simple example that gets all the recipients of a message:

fromemail.utilsimportgetaddressestos=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)

在 3.13 版的變更:Addstrict optional parameter and reject malformed inputs by default.

email.utils.parsedate(date)

Attempts to parse a date according to the rules inRFC 2822. however, somemailers don't follow that format as specified, soparsedate() tries toguess correctly in such cases.date is a string containing anRFC 2822date, such as"Mon,20Nov199519:12:08-0500". If it succeeds in parsingthe date,parsedate() returns a 9-tuple that can be passed directly totime.mktime(); otherwiseNone will be returned. Note that indexes 6,7, and 8 of the result tuple are not usable.

email.utils.parsedate_tz(date)

Performs the same function asparsedate(), but returns eitherNone ora 10-tuple; the first 9 elements make up a tuple that can be passed directly totime.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 stringhas no timezone, the last element of the tuple returned is0, which representsUTC. Note that indexes 6, 7, and 8 of the result tuple are not usable.

email.utils.parsedate_to_datetime(date)

The inverse offormat_datetime(). Performs the same function asparsedate(), but on success returns adatetime;otherwiseValueError is raised ifdate contains an invalid value suchas an hour greater than 23 or a timezone offset not between -24 and 24 hours.If the input date has a timezone of-0000, thedatetime will be a naivedatetime, and if the date is conforming to the RFCs it will represent atime in UTC but with no indication of the actual source timezone of themessage the date comes from. If the input date has any other valid timezoneoffset, thedatetime will be an awaredatetime with thecorresponding atimezonetzinfo.

在 3.3 版被加入.

email.utils.mktime_tz(tuple)

Turn a 10-tuple as returned byparsedate_tz() into a UTCtimestamp (seconds since the Epoch). If the timezone item in thetuple isNone, assume local time.

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

Returns a date string as perRFC 2822, e.g.:

Fri,09Nov200101:08:47-0000

Optionaltimeval if given is a floating-point time value as accepted bytime.gmtime() andtime.localtime(), otherwise the current time isused.

Optionallocaltime is a flag that whenTrue, interpretstimeval, andreturns a date relative to the local timezone instead of UTC, properly takingdaylight savings time into account. The default isFalse meaning UTC isused.

Optionalusegmt is a flag that whenTrue, outputs a date string with thetimezone as an ascii stringGMT, rather than a numeric-0000. This isneeded for some protocols (such as HTTP). This only applies whenlocaltime isFalse. The default isFalse.

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

Likeformatdate, but the input is adatetime instance. If it isa naive datetime, it is assumed to be "UTC with no information about thesource timezone", and the conventional-0000 is used for the timezone.If it is an awaredatetime, then the numeric timezone offset is used.If it is an aware timezone with offset zero, thenusegmt may be set toTrue, in which case the stringGMT is used instead of the numerictimezone offset. This provides a way to generate standards conformant HTTPdate headers.

在 3.3 版被加入.

email.utils.decode_rfc2231(s)

Decode the strings according toRFC 2231.

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

Encode the strings according toRFC 2231. Optionalcharset andlanguage, if given is the character set name and language name to use. Ifneither is given,s is returned as-is. Ifcharset is given butlanguageis not, the string is encoded using the empty string forlanguage.

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

When a header parameter is encoded inRFC 2231 format,Message.get_param may return a3-tuple containing the character set,language, and value.collapse_rfc2231_value() turns this into a unicodestring. Optionalerrors is passed to theerrors argument ofstr'sencode() method; it defaults to'replace'. Optionalfallback_charset specifies the character set to use if the one in theRFC 2231 header is not known by Python; it defaults to'us-ascii'.

For convenience, if thevalue passed tocollapse_rfc2231_value() is nota tuple, it should be a string and it is returned unquoted.

email.utils.decode_params(params)

Decode parameters list according toRFC 2231.params is a sequence of2-tuples containing elements of the form(content-type,string-value).

註解

[1]

Note that the sign of the timezone offset is the opposite of the sign of thetime.timezone variable for the same timezone; the latter variable followsthe POSIX standard while this module followsRFC 2822.