email.utils: 기타 유틸리티

소스 코드: Lib/email/utils.py


There are a couple of useful utilities provided in the email.utils module:

email.utils.localtime(dt=None)

Return local time as an aware datetime object. If called without arguments, return the current time. Otherwise the 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.

Added in version 3.3.

Deprecated since version 3.12, removed in version 3.14: isdst 매개 변수.

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 normally not necessary to override this default, but may be useful in certain cases, such as constructing a distributed system that uses a consistent domain name across multiple hosts.

버전 3.2에서 변경: domain 키워드가 추가되었습니다.

나머지 함수는 레거시 (Compat32) email API의 일부입니다. 이것들이 제공하는 구문 분석과 포매팅은 새 API의 헤더 구문 분석 장치가 자동으로 수행하므로, 새 API에서 이것들을 직접 사용할 필요는 없습니다.

email.utils.quote(str)

str에 있는 역 슬래시를 두 개의 역 슬래시로 대체하고, 큰따옴표는 역 슬래시-큰따옴표로 대체한 새 문자열을 반환합니다.

email.utils.unquote(str)

str의 unquote 된 버전인 새 문자열을 반환합니다. str가 큰따옴표로 끝나고 시작하면, 큰따옴표가 제거됩니다. 마찬가지로 str이 화살괄호(angle brackets)로 끝나고 시작하면, 제거됩니다.

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

address(To나 Cc와 같은 주소를 포함하는 필드의 값이어야 합니다)를 realname과 email 주소 구성 요소로 구문 분석합니다. 구문 분석에 실패하지 않는 한 해당 정보의 튜플을 반환합니다. 실패하면 ('', '')의 2-튜플이 반환됩니다.

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

버전 3.13에서 변경: Add strict optional parameter and reject malformed inputs by default.

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

The inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable for a To or Cc header. If the first element of pair is false, then the second element is returned unmodified.

선택적 charset은 realname에 비 ASCII 문자가 포함되어있을 때 realname의 RFC 2047 인코딩에 사용될 문자 집합입니다. str이나 Charset의 인스턴스가 될 수 있습니다. 기본값은 utf-8입니다.

버전 3.3에서 변경: charset 옵션이 추가되었습니다.

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

This function returns a list of 2-tuples of the form returned by parseaddr(). fieldvalues is a sequence of header field values as might be returned by Message.get_all().

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

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

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)

버전 3.13에서 변경: Add strict optional parameter and reject malformed inputs by default.

email.utils.parsedate(date)

Attempts to parse a date according to the rules in RFC 2822 Section 3.3. However, some mailers don’t follow that format as specified, so parsedate() tries to guess correctly in such cases. date is a string containing an RFC 2822 date, such as "Mon, 20 Nov 1995 19:12:08 -0500". If it succeeds in parsing the date, parsedate() returns a 9-tuple that can be passed directly to time.mktime(); otherwise None will be returned. Note that indexes 6, 7, and 8 of the result tuple are not usable.

email.utils.parsedate_tz(date)

parsedate()와 같은 기능을 수행하지만, None이나 10-튜플을 반환합니다; 앞의 9개 요소는 time.mktime()에 직접 전달할 수 있는 튜플을 구성하고, 열 번째 요소는 UTC(그리니치 표준 시의 공식 용어)로부터의 날짜의 시간대 오프셋입니다 [1]. 입력 문자열에 시간대가 없으면, 반환되는 튜플의 마지막 요소는 0입니다, UTC를 나타냅니다. 결과 튜플의 인덱스 6, 7 및 8은 사용할 수 없음에 유의하십시오.

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 conforms 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 whose corresponding tzinfo attribute is a timezone object.

Added in version 3.3.

email.utils.mktime_tz(tuple)

parsedate_tz()에 의해 반환된 10-튜플을 UTC 타임스탬프(Epoch 이후 초)로 바꿉니다. 튜플의 시간대 항목이 None이면, 지역 시간으로 간주합니다.

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

Returns a date string as per RFC 2822, for example:

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

Optional timeval, if given, is a floating-point time value as accepted by time.gmtime() and time.localtime(), otherwise the current time is used.

Optional localtime is a flag that when True, interprets timeval, and returns a date relative to the local timezone instead of UTC, properly taking daylight saving time into account. The default is False meaning UTC is used.

Optional usegmt is a flag that when True, outputs a date string with the timezone as an ASCII string GMT, rather than a numeric -0000. This is needed for some protocols (such as HTTP). This only applies when localtime is False. The default is 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.

Added in version 3.3.

email.utils.decode_rfc2231(s)

RFC 2231에 따라 s 문자열을 디코드합니다.

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

Encode the string s according to RFC 2231. Optional charset and language, if given, are the character set name and language name to use. If neither is given, s is returned as-is. If charset is given but language is not, the string is encoded using the empty string for language.

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

When a header parameter is encoded in RFC 2231 format, Message.get_param() may return a 3-tuple containing the character set, language, and value. collapse_rfc2231_value() turns this into a string. Optional errors is passed to the errors argument of str’s encode() method; it defaults to 'replace'. Optional fallback_charset specifies the character set to use if the one in the RFC 2231 header is not known by Python; it defaults to 'us-ascii'.

편의상, collapse_rfc2231_value()에 전달된 value가 튜플이 아니면, 문자열이어야 하고 unquote 되어 반환됩니다.

email.utils.decode_params(params)

RFC 2231에 따라 매개 변수 리스트를 디코드합니다. params는 (content-type, string-value) 형식의 요소를 포함하는 2-튜플의 시퀀스입니다.

각주