+++ /dev/null
-"""RFC 2822 message manipulation.\r
-\r
-Note: This is only a very rough sketch of a full RFC-822 parser; in particular\r
-the tokenizing of addresses does not adhere to all the quoting rules.\r
-\r
-Note: RFC 2822 is a long awaited update to RFC 822. This module should\r
-conform to RFC 2822, and is thus mis-named (it's not worth renaming it). Some\r
-effort at RFC 2822 updates have been made, but a thorough audit has not been\r
-performed. Consider any RFC 2822 non-conformance to be a bug.\r
-\r
- RFC 2822: http://www.faqs.org/rfcs/rfc2822.html\r
- RFC 822 : http://www.faqs.org/rfcs/rfc822.html (obsolete)\r
-\r
-Directions for use:\r
-\r
-To create a Message object: first open a file, e.g.:\r
-\r
- fp = open(file, 'r')\r
-\r
-You can use any other legal way of getting an open file object, e.g. use\r
-sys.stdin or call os.popen(). Then pass the open file object to the Message()\r
-constructor:\r
-\r
- m = Message(fp)\r
-\r
-This class can work with any input object that supports a readline method. If\r
-the input object has seek and tell capability, the rewindbody method will\r
-work; also illegal lines will be pushed back onto the input stream. If the\r
-input object lacks seek but has an `unread' method that can push back a line\r
-of input, Message will use that to push back illegal lines. Thus this class\r
-can be used to parse messages coming from a buffered stream.\r
-\r
-The optional `seekable' argument is provided as a workaround for certain stdio\r
-libraries in which tell() discards buffered data before discovering that the\r
-lseek() system call doesn't work. For maximum portability, you should set the\r
-seekable argument to zero to prevent that initial \code{tell} when passing in\r
-an unseekable object such as a a file object created from a socket object. If\r
-it is 1 on entry -- which it is by default -- the tell() method of the open\r
-file object is called once; if this raises an exception, seekable is reset to\r
-0. For other nonzero values of seekable, this test is not made.\r
-\r
-To get the text of a particular header there are several methods:\r
-\r
- str = m.getheader(name)\r
- str = m.getrawheader(name)\r
-\r
-where name is the name of the header, e.g. 'Subject'. The difference is that\r
-getheader() strips the leading and trailing whitespace, while getrawheader()\r
-doesn't. Both functions retain embedded whitespace (including newlines)\r
-exactly as they are specified in the header, and leave the case of the text\r
-unchanged.\r
-\r
-For addresses and address lists there are functions\r
-\r
- realname, mailaddress = m.getaddr(name)\r
- list = m.getaddrlist(name)\r
-\r
-where the latter returns a list of (realname, mailaddr) tuples.\r
-\r
-There is also a method\r
-\r
- time = m.getdate(name)\r
-\r
-which parses a Date-like field and returns a time-compatible tuple,\r
-i.e. a tuple such as returned by time.localtime() or accepted by\r
-time.mktime().\r
-\r
-See the class definition for lower level access methods.\r
-\r
-There are also some utility functions here.\r
-"""\r
-# Cleanup and extensions by Eric S. Raymond <esr@thyrsus.com>\r
-\r
-import time\r
-\r
-from warnings import warnpy3k\r
-warnpy3k("in 3.x, rfc822 has been removed in favor of the email package",\r
- stacklevel=2)\r
-\r
-__all__ = ["Message","AddressList","parsedate","parsedate_tz","mktime_tz"]\r
-\r
-_blanklines = ('\r\n', '\n') # Optimization for islast()\r
-\r
-\r
-class Message:\r
- """Represents a single RFC 2822-compliant message."""\r
-\r
- def __init__(self, fp, seekable = 1):\r
- """Initialize the class instance and read the headers."""\r
- if seekable == 1:\r
- # Exercise tell() to make sure it works\r
- # (and then assume seek() works, too)\r
- try:\r
- fp.tell()\r
- except (AttributeError, IOError):\r
- seekable = 0\r
- self.fp = fp\r
- self.seekable = seekable\r
- self.startofheaders = None\r
- self.startofbody = None\r
- #\r
- if self.seekable:\r
- try:\r
- self.startofheaders = self.fp.tell()\r
- except IOError:\r
- self.seekable = 0\r
- #\r
- self.readheaders()\r
- #\r
- if self.seekable:\r
- try:\r
- self.startofbody = self.fp.tell()\r
- except IOError:\r
- self.seekable = 0\r
-\r
- def rewindbody(self):\r
- """Rewind the file to the start of the body (if seekable)."""\r
- if not self.seekable:\r
- raise IOError, "unseekable file"\r
- self.fp.seek(self.startofbody)\r
-\r
- def readheaders(self):\r
- """Read header lines.\r
-\r
- Read header lines up to the entirely blank line that terminates them.\r
- The (normally blank) line that ends the headers is skipped, but not\r
- included in the returned list. If a non-header line ends the headers,\r
- (which is an error), an attempt is made to backspace over it; it is\r
- never included in the returned list.\r
-\r
- The variable self.status is set to the empty string if all went well,\r
- otherwise it is an error message. The variable self.headers is a\r
- completely uninterpreted list of lines contained in the header (so\r
- printing them will reproduce the header exactly as it appears in the\r
- file).\r
- """\r
- self.dict = {}\r
- self.unixfrom = ''\r
- self.headers = lst = []\r
- self.status = ''\r
- headerseen = ""\r
- firstline = 1\r
- startofline = unread = tell = None\r
- if hasattr(self.fp, 'unread'):\r
- unread = self.fp.unread\r
- elif self.seekable:\r
- tell = self.fp.tell\r
- while 1:\r
- if tell:\r
- try:\r
- startofline = tell()\r
- except IOError:\r
- startofline = tell = None\r
- self.seekable = 0\r
- line = self.fp.readline()\r
- if not line:\r
- self.status = 'EOF in headers'\r
- break\r
- # Skip unix From name time lines\r
- if firstline and line.startswith('From '):\r
- self.unixfrom = self.unixfrom + line\r
- continue\r
- firstline = 0\r
- if headerseen and line[0] in ' \t':\r
- # It's a continuation line.\r
- lst.append(line)\r
- x = (self.dict[headerseen] + "\n " + line.strip())\r
- self.dict[headerseen] = x.strip()\r
- continue\r
- elif self.iscomment(line):\r
- # It's a comment. Ignore it.\r
- continue\r
- elif self.islast(line):\r
- # Note! No pushback here! The delimiter line gets eaten.\r
- break\r
- headerseen = self.isheader(line)\r
- if headerseen:\r
- # It's a legal header line, save it.\r
- lst.append(line)\r
- self.dict[headerseen] = line[len(headerseen)+1:].strip()\r
- continue\r
- else:\r
- # It's not a header line; throw it back and stop here.\r
- if not self.dict:\r
- self.status = 'No headers'\r
- else:\r
- self.status = 'Non-header line where header expected'\r
- # Try to undo the read.\r
- if unread:\r
- unread(line)\r
- elif tell:\r
- self.fp.seek(startofline)\r
- else:\r
- self.status = self.status + '; bad seek'\r
- break\r
-\r
- def isheader(self, line):\r
- """Determine whether a given line is a legal header.\r
-\r
- This method should return the header name, suitably canonicalized.\r
- You may override this method in order to use Message parsing on tagged\r
- data in RFC 2822-like formats with special header formats.\r
- """\r
- i = line.find(':')\r
- if i > 0:\r
- return line[:i].lower()\r
- return None\r
-\r
- def islast(self, line):\r
- """Determine whether a line is a legal end of RFC 2822 headers.\r
-\r
- You may override this method if your application wants to bend the\r
- rules, e.g. to strip trailing whitespace, or to recognize MH template\r
- separators ('--------'). For convenience (e.g. for code reading from\r
- sockets) a line consisting of \r\n also matches.\r
- """\r
- return line in _blanklines\r
-\r
- def iscomment(self, line):\r
- """Determine whether a line should be skipped entirely.\r
-\r
- You may override this method in order to use Message parsing on tagged\r
- data in RFC 2822-like formats that support embedded comments or\r
- free-text data.\r
- """\r
- return False\r
-\r
- def getallmatchingheaders(self, name):\r
- """Find all header lines matching a given header name.\r
-\r
- Look through the list of headers and find all lines matching a given\r
- header name (and their continuation lines). A list of the lines is\r
- returned, without interpretation. If the header does not occur, an\r
- empty list is returned. If the header occurs multiple times, all\r
- occurrences are returned. Case is not important in the header name.\r
- """\r
- name = name.lower() + ':'\r
- n = len(name)\r
- lst = []\r
- hit = 0\r
- for line in self.headers:\r
- if line[:n].lower() == name:\r
- hit = 1\r
- elif not line[:1].isspace():\r
- hit = 0\r
- if hit:\r
- lst.append(line)\r
- return lst\r
-\r
- def getfirstmatchingheader(self, name):\r
- """Get the first header line matching name.\r
-\r
- This is similar to getallmatchingheaders, but it returns only the\r
- first matching header (and its continuation lines).\r
- """\r
- name = name.lower() + ':'\r
- n = len(name)\r
- lst = []\r
- hit = 0\r
- for line in self.headers:\r
- if hit:\r
- if not line[:1].isspace():\r
- break\r
- elif line[:n].lower() == name:\r
- hit = 1\r
- if hit:\r
- lst.append(line)\r
- return lst\r
-\r
- def getrawheader(self, name):\r
- """A higher-level interface to getfirstmatchingheader().\r
-\r
- Return a string containing the literal text of the header but with the\r
- keyword stripped. All leading, trailing and embedded whitespace is\r
- kept in the string, however. Return None if the header does not\r
- occur.\r
- """\r
-\r
- lst = self.getfirstmatchingheader(name)\r
- if not lst:\r
- return None\r
- lst[0] = lst[0][len(name) + 1:]\r
- return ''.join(lst)\r
-\r
- def getheader(self, name, default=None):\r
- """Get the header value for a name.\r
-\r
- This is the normal interface: it returns a stripped version of the\r
- header value for a given header name, or None if it doesn't exist.\r
- This uses the dictionary version which finds the *last* such header.\r
- """\r
- return self.dict.get(name.lower(), default)\r
- get = getheader\r
-\r
- def getheaders(self, name):\r
- """Get all values for a header.\r
-\r
- This returns a list of values for headers given more than once; each\r
- value in the result list is stripped in the same way as the result of\r
- getheader(). If the header is not given, return an empty list.\r
- """\r
- result = []\r
- current = ''\r
- have_header = 0\r
- for s in self.getallmatchingheaders(name):\r
- if s[0].isspace():\r
- if current:\r
- current = "%s\n %s" % (current, s.strip())\r
- else:\r
- current = s.strip()\r
- else:\r
- if have_header:\r
- result.append(current)\r
- current = s[s.find(":") + 1:].strip()\r
- have_header = 1\r
- if have_header:\r
- result.append(current)\r
- return result\r
-\r
- def getaddr(self, name):\r
- """Get a single address from a header, as a tuple.\r
-\r
- An example return value:\r
- ('Guido van Rossum', 'guido@cwi.nl')\r
- """\r
- # New, by Ben Escoto\r
- alist = self.getaddrlist(name)\r
- if alist:\r
- return alist[0]\r
- else:\r
- return (None, None)\r
-\r
- def getaddrlist(self, name):\r
- """Get a list of addresses from a header.\r
-\r
- Retrieves a list of addresses from a header, where each address is a\r
- tuple as returned by getaddr(). Scans all named headers, so it works\r
- properly with multiple To: or Cc: headers for example.\r
- """\r
- raw = []\r
- for h in self.getallmatchingheaders(name):\r
- if h[0] in ' \t':\r
- raw.append(h)\r
- else:\r
- if raw:\r
- raw.append(', ')\r
- i = h.find(':')\r
- if i > 0:\r
- addr = h[i+1:]\r
- raw.append(addr)\r
- alladdrs = ''.join(raw)\r
- a = AddressList(alladdrs)\r
- return a.addresslist\r
-\r
- def getdate(self, name):\r
- """Retrieve a date field from a header.\r
-\r
- Retrieves a date field from the named header, returning a tuple\r
- compatible with time.mktime().\r
- """\r
- try:\r
- data = self[name]\r
- except KeyError:\r
- return None\r
- return parsedate(data)\r
-\r
- def getdate_tz(self, name):\r
- """Retrieve a date field from a header as a 10-tuple.\r
-\r
- The first 9 elements make up a tuple compatible with time.mktime(),\r
- and the 10th is the offset of the poster's time zone from GMT/UTC.\r
- """\r
- try:\r
- data = self[name]\r
- except KeyError:\r
- return None\r
- return parsedate_tz(data)\r
-\r
-\r
- # Access as a dictionary (only finds *last* header of each type):\r
-\r
- def __len__(self):\r
- """Get the number of headers in a message."""\r
- return len(self.dict)\r
-\r
- def __getitem__(self, name):\r
- """Get a specific header, as from a dictionary."""\r
- return self.dict[name.lower()]\r
-\r
- def __setitem__(self, name, value):\r
- """Set the value of a header.\r
-\r
- Note: This is not a perfect inversion of __getitem__, because any\r
- changed headers get stuck at the end of the raw-headers list rather\r
- than where the altered header was.\r
- """\r
- del self[name] # Won't fail if it doesn't exist\r
- self.dict[name.lower()] = value\r
- text = name + ": " + value\r
- for line in text.split("\n"):\r
- self.headers.append(line + "\n")\r
-\r
- def __delitem__(self, name):\r
- """Delete all occurrences of a specific header, if it is present."""\r
- name = name.lower()\r
- if not name in self.dict:\r
- return\r
- del self.dict[name]\r
- name = name + ':'\r
- n = len(name)\r
- lst = []\r
- hit = 0\r
- for i in range(len(self.headers)):\r
- line = self.headers[i]\r
- if line[:n].lower() == name:\r
- hit = 1\r
- elif not line[:1].isspace():\r
- hit = 0\r
- if hit:\r
- lst.append(i)\r
- for i in reversed(lst):\r
- del self.headers[i]\r
-\r
- def setdefault(self, name, default=""):\r
- lowername = name.lower()\r
- if lowername in self.dict:\r
- return self.dict[lowername]\r
- else:\r
- text = name + ": " + default\r
- for line in text.split("\n"):\r
- self.headers.append(line + "\n")\r
- self.dict[lowername] = default\r
- return default\r
-\r
- def has_key(self, name):\r
- """Determine whether a message contains the named header."""\r
- return name.lower() in self.dict\r
-\r
- def __contains__(self, name):\r
- """Determine whether a message contains the named header."""\r
- return name.lower() in self.dict\r
-\r
- def __iter__(self):\r
- return iter(self.dict)\r
-\r
- def keys(self):\r
- """Get all of a message's header field names."""\r
- return self.dict.keys()\r
-\r
- def values(self):\r
- """Get all of a message's header field values."""\r
- return self.dict.values()\r
-\r
- def items(self):\r
- """Get all of a message's headers.\r
-\r
- Returns a list of name, value tuples.\r
- """\r
- return self.dict.items()\r
-\r
- def __str__(self):\r
- return ''.join(self.headers)\r
-\r
-\r
-# Utility functions\r
-# -----------------\r
-\r
-# XXX Should fix unquote() and quote() to be really conformant.\r
-# XXX The inverses of the parse functions may also be useful.\r
-\r
-\r
-def unquote(s):\r
- """Remove quotes from a string."""\r
- if len(s) > 1:\r
- if s.startswith('"') and s.endswith('"'):\r
- return s[1:-1].replace('\\\\', '\\').replace('\\"', '"')\r
- if s.startswith('<') and s.endswith('>'):\r
- return s[1:-1]\r
- return s\r
-\r
-\r
-def quote(s):\r
- """Add quotes around a string."""\r
- return s.replace('\\', '\\\\').replace('"', '\\"')\r
-\r
-\r
-def parseaddr(address):\r
- """Parse an address into a (realname, mailaddr) tuple."""\r
- a = AddressList(address)\r
- lst = a.addresslist\r
- if not lst:\r
- return (None, None)\r
- return lst[0]\r
-\r
-\r
-class AddrlistClass:\r
- """Address parser class by Ben Escoto.\r
-\r
- To understand what this class does, it helps to have a copy of\r
- RFC 2822 in front of you.\r
-\r
- http://www.faqs.org/rfcs/rfc2822.html\r
-\r
- Note: this class interface is deprecated and may be removed in the future.\r
- Use rfc822.AddressList instead.\r
- """\r
-\r
- def __init__(self, field):\r
- """Initialize a new instance.\r
-\r
- `field' is an unparsed address header field, containing one or more\r
- addresses.\r
- """\r
- self.specials = '()<>@,:;.\"[]'\r
- self.pos = 0\r
- self.LWS = ' \t'\r
- self.CR = '\r\n'\r
- self.atomends = self.specials + self.LWS + self.CR\r
- # Note that RFC 2822 now specifies `.' as obs-phrase, meaning that it\r
- # is obsolete syntax. RFC 2822 requires that we recognize obsolete\r
- # syntax, so allow dots in phrases.\r
- self.phraseends = self.atomends.replace('.', '')\r
- self.field = field\r
- self.commentlist = []\r
-\r
- def gotonext(self):\r
- """Parse up to the start of the next address."""\r
- while self.pos < len(self.field):\r
- if self.field[self.pos] in self.LWS + '\n\r':\r
- self.pos = self.pos + 1\r
- elif self.field[self.pos] == '(':\r
- self.commentlist.append(self.getcomment())\r
- else: break\r
-\r
- def getaddrlist(self):\r
- """Parse all addresses.\r
-\r
- Returns a list containing all of the addresses.\r
- """\r
- result = []\r
- ad = self.getaddress()\r
- while ad:\r
- result += ad\r
- ad = self.getaddress()\r
- return result\r
-\r
- def getaddress(self):\r
- """Parse the next address."""\r
- self.commentlist = []\r
- self.gotonext()\r
-\r
- oldpos = self.pos\r
- oldcl = self.commentlist\r
- plist = self.getphraselist()\r
-\r
- self.gotonext()\r
- returnlist = []\r
-\r
- if self.pos >= len(self.field):\r
- # Bad email address technically, no domain.\r
- if plist:\r
- returnlist = [(' '.join(self.commentlist), plist[0])]\r
-\r
- elif self.field[self.pos] in '.@':\r
- # email address is just an addrspec\r
- # this isn't very efficient since we start over\r
- self.pos = oldpos\r
- self.commentlist = oldcl\r
- addrspec = self.getaddrspec()\r
- returnlist = [(' '.join(self.commentlist), addrspec)]\r
-\r
- elif self.field[self.pos] == ':':\r
- # address is a group\r
- returnlist = []\r
-\r
- fieldlen = len(self.field)\r
- self.pos += 1\r
- while self.pos < len(self.field):\r
- self.gotonext()\r
- if self.pos < fieldlen and self.field[self.pos] == ';':\r
- self.pos += 1\r
- break\r
- returnlist = returnlist + self.getaddress()\r
-\r
- elif self.field[self.pos] == '<':\r
- # Address is a phrase then a route addr\r
- routeaddr = self.getrouteaddr()\r
-\r
- if self.commentlist:\r
- returnlist = [(' '.join(plist) + ' (' + \\r
- ' '.join(self.commentlist) + ')', routeaddr)]\r
- else: returnlist = [(' '.join(plist), routeaddr)]\r
-\r
- else:\r
- if plist:\r
- returnlist = [(' '.join(self.commentlist), plist[0])]\r
- elif self.field[self.pos] in self.specials:\r
- self.pos += 1\r
-\r
- self.gotonext()\r
- if self.pos < len(self.field) and self.field[self.pos] == ',':\r
- self.pos += 1\r
- return returnlist\r
-\r
- def getrouteaddr(self):\r
- """Parse a route address (Return-path value).\r
-\r
- This method just skips all the route stuff and returns the addrspec.\r
- """\r
- if self.field[self.pos] != '<':\r
- return\r
-\r
- expectroute = 0\r
- self.pos += 1\r
- self.gotonext()\r
- adlist = ""\r
- while self.pos < len(self.field):\r
- if expectroute:\r
- self.getdomain()\r
- expectroute = 0\r
- elif self.field[self.pos] == '>':\r
- self.pos += 1\r
- break\r
- elif self.field[self.pos] == '@':\r
- self.pos += 1\r
- expectroute = 1\r
- elif self.field[self.pos] == ':':\r
- self.pos += 1\r
- else:\r
- adlist = self.getaddrspec()\r
- self.pos += 1\r
- break\r
- self.gotonext()\r
-\r
- return adlist\r
-\r
- def getaddrspec(self):\r
- """Parse an RFC 2822 addr-spec."""\r
- aslist = []\r
-\r
- self.gotonext()\r
- while self.pos < len(self.field):\r
- if self.field[self.pos] == '.':\r
- aslist.append('.')\r
- self.pos += 1\r
- elif self.field[self.pos] == '"':\r
- aslist.append('"%s"' % self.getquote())\r
- elif self.field[self.pos] in self.atomends:\r
- break\r
- else: aslist.append(self.getatom())\r
- self.gotonext()\r
-\r
- if self.pos >= len(self.field) or self.field[self.pos] != '@':\r
- return ''.join(aslist)\r
-\r
- aslist.append('@')\r
- self.pos += 1\r
- self.gotonext()\r
- return ''.join(aslist) + self.getdomain()\r
-\r
- def getdomain(self):\r
- """Get the complete domain name from an address."""\r
- sdlist = []\r
- while self.pos < len(self.field):\r
- if self.field[self.pos] in self.LWS:\r
- self.pos += 1\r
- elif self.field[self.pos] == '(':\r
- self.commentlist.append(self.getcomment())\r
- elif self.field[self.pos] == '[':\r
- sdlist.append(self.getdomainliteral())\r
- elif self.field[self.pos] == '.':\r
- self.pos += 1\r
- sdlist.append('.')\r
- elif self.field[self.pos] in self.atomends:\r
- break\r
- else: sdlist.append(self.getatom())\r
- return ''.join(sdlist)\r
-\r
- def getdelimited(self, beginchar, endchars, allowcomments = 1):\r
- """Parse a header fragment delimited by special characters.\r
-\r
- `beginchar' is the start character for the fragment. If self is not\r
- looking at an instance of `beginchar' then getdelimited returns the\r
- empty string.\r
-\r
- `endchars' is a sequence of allowable end-delimiting characters.\r
- Parsing stops when one of these is encountered.\r
-\r
- If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed\r
- within the parsed fragment.\r
- """\r
- if self.field[self.pos] != beginchar:\r
- return ''\r
-\r
- slist = ['']\r
- quote = 0\r
- self.pos += 1\r
- while self.pos < len(self.field):\r
- if quote == 1:\r
- slist.append(self.field[self.pos])\r
- quote = 0\r
- elif self.field[self.pos] in endchars:\r
- self.pos += 1\r
- break\r
- elif allowcomments and self.field[self.pos] == '(':\r
- slist.append(self.getcomment())\r
- continue # have already advanced pos from getcomment\r
- elif self.field[self.pos] == '\\':\r
- quote = 1\r
- else:\r
- slist.append(self.field[self.pos])\r
- self.pos += 1\r
-\r
- return ''.join(slist)\r
-\r
- def getquote(self):\r
- """Get a quote-delimited fragment from self's field."""\r
- return self.getdelimited('"', '"\r', 0)\r
-\r
- def getcomment(self):\r
- """Get a parenthesis-delimited fragment from self's field."""\r
- return self.getdelimited('(', ')\r', 1)\r
-\r
- def getdomainliteral(self):\r
- """Parse an RFC 2822 domain-literal."""\r
- return '[%s]' % self.getdelimited('[', ']\r', 0)\r
-\r
- def getatom(self, atomends=None):\r
- """Parse an RFC 2822 atom.\r
-\r
- Optional atomends specifies a different set of end token delimiters\r
- (the default is to use self.atomends). This is used e.g. in\r
- getphraselist() since phrase endings must not include the `.' (which\r
- is legal in phrases)."""\r
- atomlist = ['']\r
- if atomends is None:\r
- atomends = self.atomends\r
-\r
- while self.pos < len(self.field):\r
- if self.field[self.pos] in atomends:\r
- break\r
- else: atomlist.append(self.field[self.pos])\r
- self.pos += 1\r
-\r
- return ''.join(atomlist)\r
-\r
- def getphraselist(self):\r
- """Parse a sequence of RFC 2822 phrases.\r
-\r
- A phrase is a sequence of words, which are in turn either RFC 2822\r
- atoms or quoted-strings. Phrases are canonicalized by squeezing all\r
- runs of continuous whitespace into one space.\r
- """\r
- plist = []\r
-\r
- while self.pos < len(self.field):\r
- if self.field[self.pos] in self.LWS:\r
- self.pos += 1\r
- elif self.field[self.pos] == '"':\r
- plist.append(self.getquote())\r
- elif self.field[self.pos] == '(':\r
- self.commentlist.append(self.getcomment())\r
- elif self.field[self.pos] in self.phraseends:\r
- break\r
- else:\r
- plist.append(self.getatom(self.phraseends))\r
-\r
- return plist\r
-\r
-class AddressList(AddrlistClass):\r
- """An AddressList encapsulates a list of parsed RFC 2822 addresses."""\r
- def __init__(self, field):\r
- AddrlistClass.__init__(self, field)\r
- if field:\r
- self.addresslist = self.getaddrlist()\r
- else:\r
- self.addresslist = []\r
-\r
- def __len__(self):\r
- return len(self.addresslist)\r
-\r
- def __str__(self):\r
- return ", ".join(map(dump_address_pair, self.addresslist))\r
-\r
- def __add__(self, other):\r
- # Set union\r
- newaddr = AddressList(None)\r
- newaddr.addresslist = self.addresslist[:]\r
- for x in other.addresslist:\r
- if not x in self.addresslist:\r
- newaddr.addresslist.append(x)\r
- return newaddr\r
-\r
- def __iadd__(self, other):\r
- # Set union, in-place\r
- for x in other.addresslist:\r
- if not x in self.addresslist:\r
- self.addresslist.append(x)\r
- return self\r
-\r
- def __sub__(self, other):\r
- # Set difference\r
- newaddr = AddressList(None)\r
- for x in self.addresslist:\r
- if not x in other.addresslist:\r
- newaddr.addresslist.append(x)\r
- return newaddr\r
-\r
- def __isub__(self, other):\r
- # Set difference, in-place\r
- for x in other.addresslist:\r
- if x in self.addresslist:\r
- self.addresslist.remove(x)\r
- return self\r
-\r
- def __getitem__(self, index):\r
- # Make indexing, slices, and 'in' work\r
- return self.addresslist[index]\r
-\r
-def dump_address_pair(pair):\r
- """Dump a (name, address) pair in a canonicalized form."""\r
- if pair[0]:\r
- return '"' + pair[0] + '" <' + pair[1] + '>'\r
- else:\r
- return pair[1]\r
-\r
-# Parse a date field\r
-\r
-_monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul',\r
- 'aug', 'sep', 'oct', 'nov', 'dec',\r
- 'january', 'february', 'march', 'april', 'may', 'june', 'july',\r
- 'august', 'september', 'october', 'november', 'december']\r
-_daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']\r
-\r
-# The timezone table does not include the military time zones defined\r
-# in RFC822, other than Z. According to RFC1123, the description in\r
-# RFC822 gets the signs wrong, so we can't rely on any such time\r
-# zones. RFC1123 recommends that numeric timezone indicators be used\r
-# instead of timezone names.\r
-\r
-_timezones = {'UT':0, 'UTC':0, 'GMT':0, 'Z':0,\r
- 'AST': -400, 'ADT': -300, # Atlantic (used in Canada)\r
- 'EST': -500, 'EDT': -400, # Eastern\r
- 'CST': -600, 'CDT': -500, # Central\r
- 'MST': -700, 'MDT': -600, # Mountain\r
- 'PST': -800, 'PDT': -700 # Pacific\r
- }\r
-\r
-\r
-def parsedate_tz(data):\r
- """Convert a date string to a time tuple.\r
-\r
- Accounts for military timezones.\r
- """\r
- if not data:\r
- return None\r
- data = data.split()\r
- if data[0][-1] in (',', '.') or data[0].lower() in _daynames:\r
- # There's a dayname here. Skip it\r
- del data[0]\r
- else:\r
- # no space after the "weekday,"?\r
- i = data[0].rfind(',')\r
- if i >= 0:\r
- data[0] = data[0][i+1:]\r
- if len(data) == 3: # RFC 850 date, deprecated\r
- stuff = data[0].split('-')\r
- if len(stuff) == 3:\r
- data = stuff + data[1:]\r
- if len(data) == 4:\r
- s = data[3]\r
- i = s.find('+')\r
- if i > 0:\r
- data[3:] = [s[:i], s[i+1:]]\r
- else:\r
- data.append('') # Dummy tz\r
- if len(data) < 5:\r
- return None\r
- data = data[:5]\r
- [dd, mm, yy, tm, tz] = data\r
- mm = mm.lower()\r
- if not mm in _monthnames:\r
- dd, mm = mm, dd.lower()\r
- if not mm in _monthnames:\r
- return None\r
- mm = _monthnames.index(mm)+1\r
- if mm > 12: mm = mm - 12\r
- if dd[-1] == ',':\r
- dd = dd[:-1]\r
- i = yy.find(':')\r
- if i > 0:\r
- yy, tm = tm, yy\r
- if yy[-1] == ',':\r
- yy = yy[:-1]\r
- if not yy[0].isdigit():\r
- yy, tz = tz, yy\r
- if tm[-1] == ',':\r
- tm = tm[:-1]\r
- tm = tm.split(':')\r
- if len(tm) == 2:\r
- [thh, tmm] = tm\r
- tss = '0'\r
- elif len(tm) == 3:\r
- [thh, tmm, tss] = tm\r
- else:\r
- return None\r
- try:\r
- yy = int(yy)\r
- dd = int(dd)\r
- thh = int(thh)\r
- tmm = int(tmm)\r
- tss = int(tss)\r
- except ValueError:\r
- return None\r
- tzoffset = None\r
- tz = tz.upper()\r
- if tz in _timezones:\r
- tzoffset = _timezones[tz]\r
- else:\r
- try:\r
- tzoffset = int(tz)\r
- except ValueError:\r
- pass\r
- # Convert a timezone offset into seconds ; -0500 -> -18000\r
- if tzoffset:\r
- if tzoffset < 0:\r
- tzsign = -1\r
- tzoffset = -tzoffset\r
- else:\r
- tzsign = 1\r
- tzoffset = tzsign * ( (tzoffset//100)*3600 + (tzoffset % 100)*60)\r
- return (yy, mm, dd, thh, tmm, tss, 0, 1, 0, tzoffset)\r
-\r
-\r
-def parsedate(data):\r
- """Convert a time string to a time tuple."""\r
- t = parsedate_tz(data)\r
- if t is None:\r
- return t\r
- return t[:9]\r
-\r
-\r
-def mktime_tz(data):\r
- """Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp."""\r
- if data[9] is None:\r
- # No zone info, so localtime is better assumption than GMT\r
- return time.mktime(data[:8] + (-1,))\r
- else:\r
- t = time.mktime(data[:8] + (0,))\r
- return t - data[9] - time.timezone\r
-\r
-def formatdate(timeval=None):\r
- """Returns time format preferred for Internet standards.\r
-\r
- Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123\r
-\r
- According to RFC 1123, day and month names must always be in\r
- English. If not for that, this code could use strftime(). It\r
- can't because strftime() honors the locale and could generated\r
- non-English names.\r
- """\r
- if timeval is None:\r
- timeval = time.time()\r
- timeval = time.gmtime(timeval)\r
- return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (\r
- ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[timeval[6]],\r
- timeval[2],\r
- ("Jan", "Feb", "Mar", "Apr", "May", "Jun",\r
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")[timeval[1]-1],\r
- timeval[0], timeval[3], timeval[4], timeval[5])\r
-\r
-\r
-# When used as script, run a small test program.\r
-# The first command line argument must be a filename containing one\r
-# message in RFC-822 format.\r
-\r
-if __name__ == '__main__':\r
- import sys, os\r
- file = os.path.join(os.environ['HOME'], 'Mail/inbox/1')\r
- if sys.argv[1:]: file = sys.argv[1]\r
- f = open(file, 'r')\r
- m = Message(f)\r
- print 'From:', m.getaddr('from')\r
- print 'To:', m.getaddrlist('to')\r
- print 'Subject:', m.getheader('subject')\r
- print 'Date:', m.getheader('date')\r
- date = m.getdate_tz('date')\r
- tz = date[-1]\r
- date = time.localtime(mktime_tz(date))\r
- if date:\r
- print 'ParsedDate:', time.asctime(date),\r
- hhmmss = tz\r
- hhmm, ss = divmod(hhmmss, 60)\r
- hh, mm = divmod(hhmm, 60)\r
- print "%+03d%02d" % (hh, mm),\r
- if ss: print ".%02d" % ss,\r
- print\r
- else:\r
- print 'ParsedDate:', None\r
- m.rewindbody()\r
- n = 0\r
- while f.readline():\r
- n += 1\r
- print 'Lines:', n\r
- print '-'*70\r
- print 'len =', len(m)\r
- if 'Date' in m: print 'Date =', m['Date']\r
- if 'X-Nonsense' in m: pass\r
- print 'keys =', m.keys()\r
- print 'values =', m.values()\r
- print 'items =', m.items()\r