Back to index

python3.2  3.2.2
Functions | Variables
email.utils Namespace Reference

Functions

def formataddr
def getaddresses
def formatdate
def make_msgid
def parsedate
def parsedate_tz
def parseaddr
def unquote
def decode_rfc2231
def encode_rfc2231
def decode_params
def collapse_rfc2231_value

Variables

list __all__
string COMMASPACE = ', '
string EMPTYSTRING = ''
string UEMPTYSTRING = ''
string CRLF = '\r\n'
string TICK = "'"
tuple specialsre = re.compile(r'[][\\()<>@,:;".]')escapesre = re.compile(r'[][\\()"]')
tuple ecre
tuple rfc2231_continuation

Function Documentation

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

Definition at line 294 of file utils.py.

00294 
00295                            fallback_charset='us-ascii'):
00296     if not isinstance(value, tuple) or len(value) != 3:
00297         return unquote(value)
00298     # While value comes to us as a unicode string, we need it to be a bytes
00299     # object.  We do not want bytes() normal utf-8 decoder, we want a straight
00300     # interpretation of the string as character bytes.
00301     charset, language, text = value
00302     rawbytes = bytes(text, 'raw-unicode-escape')
00303     try:
00304         return str(rawbytes, charset, errors)
00305     except LookupError:
00306         # charset is not a known codec.
00307         return unquote(text)

Here is the call graph for this function:

Here is the caller graph for this function:

def email.utils.decode_params (   params)
Decode parameters list according to RFC 2231.

params is a sequence of 2-tuples containing (param name, string value).

Definition at line 237 of file utils.py.

00237 
00238 def decode_params(params):
00239     """Decode parameters list according to RFC 2231.
00240 
00241     params is a sequence of 2-tuples containing (param name, string value).
00242     """
00243     # Copy params so we don't mess with the original
00244     params = params[:]
00245     new_params = []
00246     # Map parameter's name to a list of continuations.  The values are a
00247     # 3-tuple of the continuation number, the string value, and a flag
00248     # specifying whether a particular segment is %-encoded.
00249     rfc2231_params = {}
00250     name, value = params.pop(0)
00251     new_params.append((name, value))
00252     while params:
00253         name, value = params.pop(0)
00254         if name.endswith('*'):
00255             encoded = True
00256         else:
00257             encoded = False
00258         value = unquote(value)
00259         mo = rfc2231_continuation.match(name)
00260         if mo:
00261             name, num = mo.group('name', 'num')
00262             if num is not None:
00263                 num = int(num)
00264             rfc2231_params.setdefault(name, []).append((num, value, encoded))
00265         else:
00266             new_params.append((name, '"%s"' % quote(value)))
00267     if rfc2231_params:
00268         for name, continuations in rfc2231_params.items():
00269             value = []
00270             extended = False
00271             # Sort by number
00272             continuations.sort()
00273             # And now append all values in numerical order, converting
00274             # %-encodings for the encoded segments.  If any of the
00275             # continuation names ends in a *, then the entire string, after
00276             # decoding segments and concatenating, must have the charset and
00277             # language specifiers at the beginning of the string.
00278             for num, s, encoded in continuations:
00279                 if encoded:
00280                     # Decode as "latin-1", so the characters in s directly
00281                     # represent the percent-encoded octet values.
00282                     # collapse_rfc2231_value treats this as an octet sequence.
00283                     s = urllib.parse.unquote(s, encoding="latin-1")
00284                     extended = True
00285                 value.append(s)
00286             value = quote(EMPTYSTRING.join(value))
00287             if extended:
00288                 charset, language, value = decode_rfc2231(value)
00289                 new_params.append((name, (charset, language, '"%s"' % value)))
00290             else:
00291                 new_params.append((name, '"%s"' % value))
00292     return new_params

Here is the call graph for this function:

Decode string according to RFC 2231

Definition at line 211 of file utils.py.

00211 
00212 def decode_rfc2231(s):
00213     """Decode string according to RFC 2231"""
00214     parts = s.split(TICK, 2)
00215     if len(parts) <= 2:
00216         return None, None, s
00217     return parts
00218 

Here is the caller graph for this function:

def email.utils.encode_rfc2231 (   s,
  charset = None,
  language = None 
)
Encode string according to RFC 2231.

If neither charset nor language is given, then s is returned as-is.  If
charset is given but not language, the string is encoded using the empty
string for language.

Definition at line 219 of file utils.py.

00219 
00220 def encode_rfc2231(s, charset=None, language=None):
00221     """Encode string according to RFC 2231.
00222 
00223     If neither charset nor language is given, then s is returned as-is.  If
00224     charset is given but not language, the string is encoded using the empty
00225     string for language.
00226     """
00227     s = urllib.parse.quote(s, safe='', encoding=charset or 'ascii')
00228     if charset is None and language is None:
00229         return s
00230     if language is None:
00231         language = ''
00232     return "%s'%s'%s" % (charset, language, s)
00233 

Here is the call graph for this function:

def email.utils.formataddr (   pair)
The inverse of parseaddr(), this takes a 2-tuple of the form
(realname, email_address) and returns the string value suitable
for an RFC 2822 From, To or Cc header.

If the first element of pair is false, then the second element is
returned unmodified.

Definition at line 59 of file utils.py.

00059 
00060 def formataddr(pair):
00061     """The inverse of parseaddr(), this takes a 2-tuple of the form
00062     (realname, email_address) and returns the string value suitable
00063     for an RFC 2822 From, To or Cc header.
00064 
00065     If the first element of pair is false, then the second element is
00066     returned unmodified.
00067     """
00068     name, address = pair
00069     if name:
00070         quotes = ''
00071         if specialsre.search(name):
00072             quotes = '"'
00073         name = escapesre.sub(r'\\\g<0>', name)
00074         return '%s%s%s <%s>' % (quotes, name, quotes, address)
00075     return address
00076 
00077 

def email.utils.formatdate (   timeval = None,
  localtime = False,
  usegmt = False 
)
Returns a date string as specified by RFC 2822, e.g.:

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

Optional timeval if given is a floating point time value as accepted by
gmtime() and 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 savings time into account.

Optional argument usegmt means that the timezone is written out as
an ascii string, not numeric one (so "GMT" instead of "+0000"). This
is needed for HTTP, and is only used when localtime==False.

Definition at line 98 of file utils.py.

00098 
00099 def formatdate(timeval=None, localtime=False, usegmt=False):
00100     """Returns a date string as specified by RFC 2822, e.g.:
00101 
00102     Fri, 09 Nov 2001 01:08:47 -0000
00103 
00104     Optional timeval if given is a floating point time value as accepted by
00105     gmtime() and localtime(), otherwise the current time is used.
00106 
00107     Optional localtime is a flag that when True, interprets timeval, and
00108     returns a date relative to the local timezone instead of UTC, properly
00109     taking daylight savings time into account.
00110 
00111     Optional argument usegmt means that the timezone is written out as
00112     an ascii string, not numeric one (so "GMT" instead of "+0000"). This
00113     is needed for HTTP, and is only used when localtime==False.
00114     """
00115     # Note: we cannot use strftime() because that honors the locale and RFC
00116     # 2822 requires that day and month names be the English abbreviations.
00117     if timeval is None:
00118         timeval = time.time()
00119     if localtime:
00120         now = time.localtime(timeval)
00121         # Calculate timezone offset, based on whether the local zone has
00122         # daylight savings time, and whether DST is in effect.
00123         if time.daylight and now[-1]:
00124             offset = time.altzone
00125         else:
00126             offset = time.timezone
00127         hours, minutes = divmod(abs(offset), 3600)
00128         # Remember offset is in seconds west of UTC, but the timezone is in
00129         # minutes east of UTC, so the signs differ.
00130         if offset > 0:
00131             sign = '-'
00132         else:
00133             sign = '+'
00134         zone = '%s%02d%02d' % (sign, hours, minutes // 60)
00135     else:
00136         now = time.gmtime(timeval)
00137         # Timezone offset is always -0000
00138         if usegmt:
00139             zone = 'GMT'
00140         else:
00141             zone = '-0000'
00142     return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
00143         ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]],
00144         now[2],
00145         ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
00146          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1],
00147         now[0], now[3], now[4], now[5],
00148         zone)
00149 
00150 

Here is the call graph for this function:

Here is the caller graph for this function:

def email.utils.getaddresses (   fieldvalues)
Return a list of (REALNAME, EMAIL) for each fieldvalue.

Definition at line 78 of file utils.py.

00078 
00079 def getaddresses(fieldvalues):
00080     """Return a list of (REALNAME, EMAIL) for each fieldvalue."""
00081     all = COMMASPACE.join(fieldvalues)
00082     a = _AddressList(all)
00083     return a.addresslist
00084 
00085 

Here is the caller graph for this function:

def email.utils.make_msgid (   idstring = None,
  domain = None 
)
Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

<20020201195627.33539.96671@nightshade.la.mastaler.com>

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 message id after the '@'.  It defaults to the locally
defined hostname.

Definition at line 151 of file utils.py.

00151 
00152 def make_msgid(idstring=None, domain=None):
00153     """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
00154 
00155     <20020201195627.33539.96671@nightshade.la.mastaler.com>
00156 
00157     Optional idstring if given is a string used to strengthen the
00158     uniqueness of the message id.  Optional domain if given provides the
00159     portion of the message id after the '@'.  It defaults to the locally
00160     defined hostname.
00161     """
00162     timeval = time.time()
00163     utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
00164     pid = os.getpid()
00165     randint = random.randrange(100000)
00166     if idstring is None:
00167         idstring = ''
00168     else:
00169         idstring = '.' + idstring
00170     if domain is None:
00171         domain = socket.getfqdn()
00172     msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, domain)
00173     return msgid
00174 
00175 
00176 
00177 # These functions are in the standalone mimelib version only because they've
00178 # subsequently been fixed in the latest Python versions.  We use this to worm
# around broken older Pythons.

Here is the call graph for this function:

Here is the caller graph for this function:

def email.utils.parseaddr (   addr)

Definition at line 191 of file utils.py.

00191 
00192 def parseaddr(addr):
00193     addrs = _AddressList(addr).addresslist
00194     if not addrs:
00195         return '', ''
00196     return addrs[0]
00197 
00198 
# rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3.

Here is the caller graph for this function:

def email.utils.parsedate (   data)

Definition at line 179 of file utils.py.

00179 
00180 def parsedate(data):
00181     if not data:
00182         return None
00183     return _parsedate(data)
00184 

def email.utils.parsedate_tz (   data)

Definition at line 185 of file utils.py.

00185 
00186 def parsedate_tz(data):
00187     if not data:
00188         return None
00189     return _parsedate_tz(data)
00190 

def email.utils.unquote (   str)
Remove quotes from a string.

Definition at line 199 of file utils.py.

00199 
00200 def unquote(str):
00201     """Remove quotes from a string."""
00202     if len(str) > 1:
00203         if str.startswith('"') and str.endswith('"'):
00204             return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
00205         if str.startswith('<') and str.endswith('>'):
00206             return str[1:-1]
00207     return str
00208 
00209 
00210 
# RFC2231-related functions - parameter encoding and decoding

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 [
00002     'collapse_rfc2231_value',
00003     'decode_params',
00004     'decode_rfc2231',
00005     'encode_rfc2231',
00006     'formataddr',
00007     'formatdate',
00008     'getaddresses',
00009     'make_msgid',
00010     'mktime_tz',
00011     'parseaddr',
00012     'parsedate',
00013     'parsedate_tz',
00014     'unquote',
00015     ]

Definition at line 7 of file utils.py.

Definition at line 46 of file utils.py.

Definition at line 49 of file utils.py.

Initial value:
00001 re.compile(r'''
00002   =\?                   # literal =?
00003   (?P<charset>[^?]*?)   # non-greedy up to the next ? is the charset
00004   \?                    # literal ?
00005   (?P<encoding>[qb])    # either a "q" or a "b", case insensitive
00006   \?                    # literal ?
00007   (?P<atom>.*?)         # non-greedy up to the next ?= is the atom
00008   \?=                   # literal ?=
00009   ''', re.VERBOSE | re.IGNORECASE)

Definition at line 86 of file utils.py.

Definition at line 47 of file utils.py.

Initial value:
00001 re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$',
00002     re.ASCII)

Definition at line 234 of file utils.py.

tuple email.utils.specialsre = re.compile(r'[][\\()<>@,:;".]')escapesre = re.compile(r'[][\\()"]')

Definition at line 52 of file utils.py.

Definition at line 50 of file utils.py.

Definition at line 48 of file utils.py.