Movatterモバイル変換


[0]ホーム

URL:


Navigation

19.1.11.email.utils: Miscellaneous utilities

There are several useful utilities provided in theemail.utils module:

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)

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.

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.

Changed in version 3.3:Added thecharset option.

email.utils.getaddresses(fieldvalues)

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. Here’s a simpleexample 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)
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 isNone. Note thatindexes 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. Ifthe 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.

New in version 3.3.

email.utils.mktime_tz(tuple)

Turn a 10-tuple as returned byparsedate_tz() into a UTC timestamp. Itthe timezone item in the tuple isNone, assume local time. Minordeficiency:mktime_tz() interprets the first 8 elements oftuple as alocal time and then compensates for the timezone difference. This may yield aslight error around changes in daylight savings time, though not worth worryingabout for common use.

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.

New in version 3.3.

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. In thiscase, a positive or zero value forisdst causeslocaltime to presumeinitially that summer time (for example, Daylight Saving Time) is or is not(respectively) in effect for the specified time. A negative value forisdst causes thelocaltime to attempt to divine whether summer timeis in effect for the specified time.

New in version 3.3.

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.

Changed in version 3.2:Added thedomain keyword.

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).

Footnotes

[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.

Previous topic

19.1.10.email.errors: Exception and Defect classes

Next topic

19.1.12.email.iterators: Iterators

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Sep 19, 2017.Found a bug?
Created usingSphinx 1.2.

[8]ページ先頭

©2009-2025 Movatter.jp