home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / iria107a.lzh / script / rfc822.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2000-11-17  |  34.4 KB  |  1,059 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.0)
  3.  
  4. """RFC-822 message manipulation class.
  5.  
  6. XXX This is only a very rough sketch of a full RFC-822 parser;
  7. in particular the tokenizing of addresses does not adhere to all the
  8. quoting rules.
  9.  
  10. Directions for use:
  11.  
  12. To create a Message object: first open a file, e.g.:
  13.   fp = open(file, 'r')
  14. You can use any other legal way of getting an open file object, e.g. use
  15. sys.stdin or call os.popen().
  16. Then pass the open file object to the Message() constructor:
  17.   m = Message(fp)
  18.  
  19. This class can work with any input object that supports a readline
  20. method.  If the input object has seek and tell capability, the
  21. rewindbody method will work; also illegal lines will be pushed back
  22. onto the input stream.  If the input object lacks seek but has an
  23. `unread' method that can push back a line of input, Message will use
  24. that to push back illegal lines.  Thus this class can be used to parse
  25. messages coming from a buffered stream.
  26.  
  27. The optional `seekable' argument is provided as a workaround for
  28. certain stdio libraries in which tell() discards buffered data before
  29. discovering that the lseek() system call doesn't work.  For maximum
  30. portability, you should set the seekable argument to zero to prevent
  31. that initial \\code{tell} when passing in an unseekable object such as
  32. a a file object created from a socket object.  If it is 1 on entry --
  33. which it is by default -- the tell() method of the open file object is
  34. called once; if this raises an exception, seekable is reset to 0.  For 
  35. other nonzero values of seekable, this test is not made.
  36.  
  37. To get the text of a particular header there are several methods:
  38.   str = m.getheader(name)
  39.   str = m.getrawheader(name)
  40. where name is the name of the header, e.g. 'Subject'.
  41. The difference is that getheader() strips the leading and trailing
  42. whitespace, while getrawheader() doesn't.  Both functions retain
  43. embedded whitespace (including newlines) exactly as they are
  44. specified in the header, and leave the case of the text unchanged.
  45.  
  46. For addresses and address lists there are functions
  47.   realname, mailaddress = m.getaddr(name) and
  48.   list = m.getaddrlist(name)
  49. where the latter returns a list of (realname, mailaddr) tuples.
  50.  
  51. There is also a method
  52.   time = m.getdate(name)
  53. which parses a Date-like field and returns a time-compatible tuple,
  54. i.e. a tuple such as returned by time.localtime() or accepted by
  55. time.mktime().
  56.  
  57. See the class definition for lower level access methods.
  58.  
  59. There are also some utility functions here.
  60. """
  61. import string
  62. import time
  63. _blanklines = ('\r\n', '\n')
  64.  
  65. class Message:
  66.     '''Represents a single RFC-822-compliant message.'''
  67.     
  68.     def __init__(self, fp, seekable = 1):
  69.         '''Initialize the class instance and read the headers.'''
  70.         if seekable == 1:
  71.             
  72.             try:
  73.                 fp.tell()
  74.             except:
  75.                 seekable = 0
  76.  
  77.             seekable = 1
  78.         
  79.         self.fp = fp
  80.         self.seekable = seekable
  81.         self.startofheaders = None
  82.         self.startofbody = None
  83.         if self.seekable:
  84.             
  85.             try:
  86.                 self.startofheaders = self.fp.tell()
  87.             except IOError:
  88.                 self.seekable = 0
  89.  
  90.         
  91.         self.readheaders()
  92.         if self.seekable:
  93.             
  94.             try:
  95.                 self.startofbody = self.fp.tell()
  96.             except IOError:
  97.                 self.seekable = 0
  98.  
  99.         
  100.  
  101.     
  102.     def rewindbody(self):
  103.         '''Rewind the file to the start of the body (if seekable).'''
  104.         if not (self.seekable):
  105.             raise IOError, 'unseekable file'
  106.         
  107.         self.fp.seek(self.startofbody)
  108.  
  109.     
  110.     def readheaders(self):
  111.         '''Read header lines.
  112.         
  113.         Read header lines up to the entirely blank line that
  114.         terminates them.  The (normally blank) line that ends the
  115.         headers is skipped, but not included in the returned list.
  116.         If a non-header line ends the headers, (which is an error),
  117.         an attempt is made to backspace over it; it is never
  118.         included in the returned list.
  119.         
  120.         The variable self.status is set to the empty string if all
  121.         went well, otherwise it is an error message.
  122.         The variable self.headers is a completely uninterpreted list
  123.         of lines contained in the header (so printing them will
  124.         reproduce the header exactly as it appears in the file).
  125.         '''
  126.         self.dict = { }
  127.         self.unixfrom = ''
  128.         self.headers = list = []
  129.         self.status = ''
  130.         headerseen = ''
  131.         firstline = 1
  132.         startofline = unread = tell = None
  133.         if hasattr(self.fp, 'unread'):
  134.             unread = self.fp.unread
  135.         elif self.seekable:
  136.             tell = self.fp.tell
  137.         
  138.         while 1:
  139.             if tell:
  140.                 startofline = tell()
  141.             
  142.             line = self.fp.readline()
  143.             if not line:
  144.                 self.status = 'EOF in headers'
  145.                 break
  146.             
  147.             if firstline and line[:5] == 'From ':
  148.                 self.unixfrom = self.unixfrom + line
  149.                 continue
  150.             
  151.             firstline = 0
  152.             if headerseen and line[0] in ' \t':
  153.                 list.append(line)
  154.                 x = self.dict[headerseen] + '\n ' + string.strip(line)
  155.                 self.dict[headerseen] = string.strip(x)
  156.                 continue
  157.             elif self.iscomment(line):
  158.                 continue
  159.             elif self.islast(line):
  160.                 break
  161.             
  162.             headerseen = self.isheader(line)
  163.             if headerseen:
  164.                 list.append(line)
  165.                 self.dict[headerseen] = string.strip(line[len(headerseen) + 1:])
  166.                 continue
  167.             elif not (self.dict):
  168.                 self.status = 'No headers'
  169.             else:
  170.                 self.status = 'Non-header line where header expected'
  171.             if unread:
  172.                 unread(line)
  173.             elif tell:
  174.                 self.fp.seek(startofline)
  175.             else:
  176.                 self.status = self.status + '; bad seek'
  177.             break
  178.  
  179.     
  180.     def isheader(self, line):
  181.         '''Determine whether a given line is a legal header.
  182.  
  183.         This method should return the header name, suitably canonicalized.
  184.         You may override this method in order to use Message parsing
  185.         on tagged data in RFC822-like formats with special header formats.
  186.         '''
  187.         i = string.find(line, ':')
  188.         if i > 0:
  189.             return string.lower(line[:i])
  190.         else:
  191.             return None
  192.  
  193.     
  194.     def islast(self, line):
  195.         """Determine whether a line is a legal end of RFC-822 headers.
  196.         
  197.         You may override this method if your application wants
  198.         to bend the rules, e.g. to strip trailing whitespace,
  199.         or to recognize MH template separators ('--------').
  200.         For convenience (e.g. for code reading from sockets) a
  201.         line consisting of \r
  202.  also matches.                
  203.         """
  204.         return line in _blanklines
  205.  
  206.     
  207.     def iscomment(self, line):
  208.         '''Determine whether a line should be skipped entirely.
  209.  
  210.         You may override this method in order to use Message parsing
  211.         on tagged data in RFC822-like formats that support embedded
  212.         comments or free-text data.
  213.         '''
  214.         return None
  215.  
  216.     
  217.     def getallmatchingheaders(self, name):
  218.         '''Find all header lines matching a given header name.
  219.         
  220.         Look through the list of headers and find all lines
  221.         matching a given header name (and their continuation
  222.         lines).  A list of the lines is returned, without
  223.         interpretation.  If the header does not occur, an
  224.         empty list is returned.  If the header occurs multiple
  225.         times, all occurrences are returned.  Case is not
  226.         important in the header name.
  227.         '''
  228.         name = string.lower(name) + ':'
  229.         n = len(name)
  230.         list = []
  231.         hit = 0
  232.         for line in self.headers:
  233.             if string.lower(line[:n]) == name:
  234.                 hit = 1
  235.             elif line[:1] not in string.whitespace:
  236.                 hit = 0
  237.             
  238.             if hit:
  239.                 list.append(line)
  240.             
  241.         
  242.         return list
  243.  
  244.     
  245.     def getfirstmatchingheader(self, name):
  246.         '''Get the first header line matching name.
  247.         
  248.         This is similar to getallmatchingheaders, but it returns
  249.         only the first matching header (and its continuation
  250.         lines).
  251.         '''
  252.         name = string.lower(name) + ':'
  253.         n = len(name)
  254.         list = []
  255.         hit = 0
  256.         for line in self.headers:
  257.             if hit:
  258.                 if line[:1] not in string.whitespace:
  259.                     break
  260.                 
  261.             elif string.lower(line[:n]) == name:
  262.                 hit = 1
  263.             
  264.         
  265.         return list
  266.  
  267.     
  268.     def getrawheader(self, name):
  269.         '''A higher-level interface to getfirstmatchingheader().
  270.         
  271.         Return a string containing the literal text of the
  272.         header but with the keyword stripped.  All leading,
  273.         trailing and embedded whitespace is kept in the
  274.         string, however.
  275.         Return None if the header does not occur.
  276.         '''
  277.         list = self.getfirstmatchingheader(name)
  278.         if not list:
  279.             return None
  280.         
  281.         list[0] = list[0][len(name) + 1:]
  282.         return string.joinfields(list, '')
  283.  
  284.     
  285.     def getheader(self, name, default = None):
  286.         """Get the header value for a name.
  287.         
  288.         This is the normal interface: it returns a stripped
  289.         version of the header value for a given header name,
  290.         or None if it doesn't exist.  This uses the dictionary
  291.         version which finds the *last* such header.
  292.         """
  293.         
  294.         try:
  295.             return self.dict[string.lower(name)]
  296.         except KeyError:
  297.             return default
  298.  
  299.  
  300.     get = getheader
  301.     
  302.     def getheaders(self, name):
  303.         '''Get all values for a header.
  304.  
  305.         This returns a list of values for headers given more than once;
  306.         each value in the result list is stripped in the same way as the
  307.         result of getheader().  If the header is not given, return an
  308.         empty list.
  309.         '''
  310.         result = []
  311.         current = ''
  312.         have_header = 0
  313.         for s in self.getallmatchingheaders(name):
  314.             if s[0] in string.whitespace:
  315.                 if current:
  316.                     current = '%s\n %s' % (current, string.strip(s))
  317.                 else:
  318.                     current = string.strip(s)
  319.             elif have_header:
  320.                 result.append(current)
  321.             
  322.             current = string.strip(s[string.find(s, ':') + 1:])
  323.             have_header = 1
  324.         
  325.         return result
  326.  
  327.     
  328.     def getaddr(self, name):
  329.         """Get a single address from a header, as a tuple.
  330.         
  331.         An example return value:
  332.         ('Guido van Rossum', 'guido@cwi.nl')
  333.         """
  334.         alist = self.getaddrlist(name)
  335.         if alist:
  336.             return alist[0]
  337.         else:
  338.             return (None, None)
  339.  
  340.     
  341.     def getaddrlist(self, name):
  342.         '''Get a list of addresses from a header.
  343.  
  344.         Retrieves a list of addresses from a header, where each address is a
  345.         tuple as returned by getaddr().  Scans all named headers, so it works
  346.         properly with multiple To: or Cc: headers for example.
  347.  
  348.         '''
  349.         raw = []
  350.         for h in self.getallmatchingheaders(name):
  351.             if h[0] in ' \t':
  352.                 raw.append(h)
  353.             elif raw:
  354.                 raw.append(', ')
  355.             
  356.             i = string.find(h, ':')
  357.             if i > 0:
  358.                 addr = h[i + 1:]
  359.             
  360.             raw.append(addr)
  361.         
  362.         alladdrs = string.join(raw, '')
  363.         a = AddrlistClass(alladdrs)
  364.         return a.getaddrlist()
  365.  
  366.     
  367.     def getdate(self, name):
  368.         '''Retrieve a date field from a header.
  369.         
  370.         Retrieves a date field from the named header, returning
  371.         a tuple compatible with time.mktime().
  372.         '''
  373.         
  374.         try:
  375.             data = self[name]
  376.         except KeyError:
  377.             return None
  378.  
  379.         return parsedate(data)
  380.  
  381.     
  382.     def getdate_tz(self, name):
  383.         """Retrieve a date field from a header as a 10-tuple.
  384.         
  385.         The first 9 elements make up a tuple compatible with
  386.         time.mktime(), and the 10th is the offset of the poster's
  387.         time zone from GMT/UTC.
  388.         """
  389.         
  390.         try:
  391.             data = self[name]
  392.         except KeyError:
  393.             return None
  394.  
  395.         return parsedate_tz(data)
  396.  
  397.     
  398.     def __len__(self):
  399.         '''Get the number of headers in a message.'''
  400.         return len(self.dict)
  401.  
  402.     
  403.     def __getitem__(self, name):
  404.         '''Get a specific header, as from a dictionary.'''
  405.         return self.dict[string.lower(name)]
  406.  
  407.     
  408.     def __setitem__(self, name, value):
  409.         '''Set the value of a header.
  410.  
  411.         Note: This is not a perfect inversion of __getitem__, because 
  412.         any changed headers get stuck at the end of the raw-headers list
  413.         rather than where the altered header was.
  414.         '''
  415.         del self[name]
  416.         self.dict[string.lower(name)] = value
  417.         text = name + ': ' + value
  418.         lines = string.split(text, '\n')
  419.         for line in lines:
  420.             self.headers.append(line + '\n')
  421.         
  422.  
  423.     
  424.     def __delitem__(self, name):
  425.         '''Delete all occurrences of a specific header, if it is present.'''
  426.         name = string.lower(name)
  427.         if not self.dict.has_key(name):
  428.             return None
  429.         
  430.         del self.dict[name]
  431.         name = name + ':'
  432.         n = len(name)
  433.         list = []
  434.         hit = 0
  435.         for i in range(len(self.headers)):
  436.             line = self.headers[i]
  437.             if string.lower(line[:n]) == name:
  438.                 hit = 1
  439.             elif line[:1] not in string.whitespace:
  440.                 hit = 0
  441.             
  442.             if hit:
  443.                 list.append(i)
  444.             
  445.         
  446.         list.reverse()
  447.         for i in list:
  448.             del self.headers[i]
  449.         
  450.  
  451.     
  452.     def has_key(self, name):
  453.         '''Determine whether a message contains the named header.'''
  454.         return self.dict.has_key(string.lower(name))
  455.  
  456.     
  457.     def keys(self):
  458.         """Get all of a message's header field names."""
  459.         return self.dict.keys()
  460.  
  461.     
  462.     def values(self):
  463.         """Get all of a message's header field values."""
  464.         return self.dict.values()
  465.  
  466.     
  467.     def items(self):
  468.         """Get all of a message's headers.
  469.         
  470.         Returns a list of name, value tuples.
  471.         """
  472.         return self.dict.items()
  473.  
  474.     
  475.     def __str__(self):
  476.         str = ''
  477.         for hdr in self.headers:
  478.             str = str + hdr
  479.         
  480.         return str
  481.  
  482.  
  483.  
  484. def unquote(str):
  485.     '''Remove quotes from a string.'''
  486.     if len(str) > 1:
  487.         if str[0] == '"' and str[-1:] == '"':
  488.             return str[1:-1]
  489.         
  490.         if str[0] == '<' and str[-1:] == '>':
  491.             return str[1:-1]
  492.         
  493.     
  494.     return str
  495.  
  496.  
  497. def quote(str):
  498.     '''Add quotes around a string.'''
  499.     return '"%s"' % string.join(string.split(string.join(string.split(str, '\\'), '\\\\'), '"'), '\\"')
  500.  
  501.  
  502. def parseaddr(address):
  503.     '''Parse an address into a (realname, mailaddr) tuple.'''
  504.     a = AddrlistClass(address)
  505.     list = a.getaddrlist()
  506.     if not list:
  507.         return (None, None)
  508.     else:
  509.         return list[0]
  510.  
  511.  
  512. class AddrlistClass:
  513.     '''Address parser class by Ben Escoto.
  514.     
  515.     To understand what this class does, it helps to have a copy of
  516.     RFC-822 in front of you.
  517.  
  518.     Note: this class interface is deprecated and may be removed in the future.
  519.     Use rfc822.AddressList instead.
  520.     '''
  521.     
  522.     def __init__(self, field):
  523.         """Initialize a new instance.
  524.         
  525.         `field' is an unparsed address header field, containing
  526.         one or more addresses.
  527.         """
  528.         self.specials = '()<>@,:;."[]'
  529.         self.pos = 0
  530.         self.LWS = ' \t'
  531.         self.CR = '\r\n'
  532.         self.atomends = self.specials + self.LWS + self.CR
  533.         self.field = field
  534.         self.commentlist = []
  535.  
  536.     
  537.     def gotonext(self):
  538.         '''Parse up to the start of the next address.'''
  539.         while self.pos < len(self.field):
  540.             if self.field[self.pos] in self.LWS + '\n\r':
  541.                 self.pos = self.pos + 1
  542.             elif self.field[self.pos] == '(':
  543.                 self.commentlist.append(self.getcomment())
  544.             else:
  545.                 break
  546.  
  547.     
  548.     def getaddrlist(self):
  549.         '''Parse all addresses.
  550.         
  551.         Returns a list containing all of the addresses.
  552.         '''
  553.         ad = self.getaddress()
  554.         if ad:
  555.             return ad + self.getaddrlist()
  556.         else:
  557.             return []
  558.  
  559.     
  560.     def getaddress(self):
  561.         '''Parse the next address.'''
  562.         self.commentlist = []
  563.         self.gotonext()
  564.         oldpos = self.pos
  565.         oldcl = self.commentlist
  566.         plist = self.getphraselist()
  567.         self.gotonext()
  568.         returnlist = []
  569.         if self.pos >= len(self.field):
  570.             if plist:
  571.                 returnlist = [
  572.                     (string.join(self.commentlist), plist[0])]
  573.             
  574.         elif self.field[self.pos] in '.@':
  575.             self.pos = oldpos
  576.             self.commentlist = oldcl
  577.             addrspec = self.getaddrspec()
  578.             returnlist = [
  579.                 (string.join(self.commentlist), addrspec)]
  580.         elif self.field[self.pos] == ':':
  581.             returnlist = []
  582.             fieldlen = len(self.field)
  583.             self.pos = self.pos + 1
  584.             while self.pos < len(self.field):
  585.                 self.gotonext()
  586.                 if self.pos < fieldlen and self.field[self.pos] == ';':
  587.                     self.pos = self.pos + 1
  588.                     break
  589.                 
  590.                 returnlist = returnlist + self.getaddress()
  591.         elif self.field[self.pos] == '<':
  592.             routeaddr = self.getrouteaddr()
  593.             if self.commentlist:
  594.                 returnlist = [
  595.                     (string.join(plist) + ' (' + string.join(self.commentlist) + ')', routeaddr)]
  596.             else:
  597.                 returnlist = [
  598.                     (string.join(plist), routeaddr)]
  599.         elif plist:
  600.             returnlist = [
  601.                 (string.join(self.commentlist), plist[0])]
  602.         elif self.field[self.pos] in self.specials:
  603.             self.pos = self.pos + 1
  604.         
  605.         self.gotonext()
  606.         if self.pos < len(self.field) and self.field[self.pos] == ',':
  607.             self.pos = self.pos + 1
  608.         
  609.         return returnlist
  610.  
  611.     
  612.     def getrouteaddr(self):
  613.         '''Parse a route address (Return-path value).
  614.         
  615.         This method just skips all the route stuff and returns the addrspec.
  616.         '''
  617.         if self.field[self.pos] != '<':
  618.             return None
  619.         
  620.         expectroute = 0
  621.         self.pos = self.pos + 1
  622.         self.gotonext()
  623.         adlist = None
  624.         while self.pos < len(self.field):
  625.             if expectroute:
  626.                 self.getdomain()
  627.                 expectroute = 0
  628.             elif self.field[self.pos] == '>':
  629.                 self.pos = self.pos + 1
  630.                 break
  631.             elif self.field[self.pos] == '@':
  632.                 self.pos = self.pos + 1
  633.                 expectroute = 1
  634.             elif self.field[self.pos] == ':':
  635.                 self.pos = self.pos + 1
  636.                 expectaddrspec = 1
  637.             else:
  638.                 adlist = self.getaddrspec()
  639.                 self.pos = self.pos + 1
  640.                 break
  641.             self.gotonext()
  642.         return adlist
  643.  
  644.     
  645.     def getaddrspec(self):
  646.         '''Parse an RFC-822 addr-spec.'''
  647.         aslist = []
  648.         self.gotonext()
  649.         while self.pos < len(self.field):
  650.             if self.field[self.pos] == '.':
  651.                 aslist.append('.')
  652.                 self.pos = self.pos + 1
  653.             elif self.field[self.pos] == '"':
  654.                 aslist.append('"%s"' % self.getquote())
  655.             elif self.field[self.pos] in self.atomends:
  656.                 break
  657.             else:
  658.                 aslist.append(self.getatom())
  659.             self.gotonext()
  660.         if self.pos >= len(self.field) or self.field[self.pos] != '@':
  661.             return string.join(aslist, '')
  662.         
  663.         aslist.append('@')
  664.         self.pos = self.pos + 1
  665.         self.gotonext()
  666.         return string.join(aslist, '') + self.getdomain()
  667.  
  668.     
  669.     def getdomain(self):
  670.         '''Get the complete domain name from an address.'''
  671.         sdlist = []
  672.         while self.pos < len(self.field):
  673.             if self.field[self.pos] in self.LWS:
  674.                 self.pos = self.pos + 1
  675.             elif self.field[self.pos] == '(':
  676.                 self.commentlist.append(self.getcomment())
  677.             elif self.field[self.pos] == '[':
  678.                 sdlist.append(self.getdomainliteral())
  679.             elif self.field[self.pos] == '.':
  680.                 self.pos = self.pos + 1
  681.                 sdlist.append('.')
  682.             elif self.field[self.pos] in self.atomends:
  683.                 break
  684.             else:
  685.                 sdlist.append(self.getatom())
  686.         return string.join(sdlist, '')
  687.  
  688.     
  689.     def getdelimited(self, beginchar, endchars, allowcomments = 1):
  690.         """Parse a header fragment delimited by special characters.
  691.         
  692.         `beginchar' is the start character for the fragment.
  693.         If self is not looking at an instance of `beginchar' then
  694.         getdelimited returns the empty string.
  695.         
  696.         `endchars' is a sequence of allowable end-delimiting characters.
  697.         Parsing stops when one of these is encountered.
  698.         
  699.         If `allowcomments' is non-zero, embedded RFC-822 comments
  700.         are allowed within the parsed fragment.
  701.         """
  702.         if self.field[self.pos] != beginchar:
  703.             return ''
  704.         
  705.         slist = [
  706.             '']
  707.         quote = 0
  708.         self.pos = self.pos + 1
  709.         while self.pos < len(self.field):
  710.             if quote == 1:
  711.                 slist.append(self.field[self.pos])
  712.                 quote = 0
  713.             elif self.field[self.pos] in endchars:
  714.                 self.pos = self.pos + 1
  715.                 break
  716.             elif allowcomments and self.field[self.pos] == '(':
  717.                 slist.append(self.getcomment())
  718.             elif self.field[self.pos] == '\\':
  719.                 quote = 1
  720.             else:
  721.                 slist.append(self.field[self.pos])
  722.             self.pos = self.pos + 1
  723.         return string.join(slist, '')
  724.  
  725.     
  726.     def getquote(self):
  727.         """Get a quote-delimited fragment from self's field."""
  728.         return self.getdelimited('"', '"\r', 0)
  729.  
  730.     
  731.     def getcomment(self):
  732.         """Get a parenthesis-delimited fragment from self's field."""
  733.         return self.getdelimited('(', ')\r', 1)
  734.  
  735.     
  736.     def getdomainliteral(self):
  737.         '''Parse an RFC-822 domain-literal.'''
  738.         return '[%s]' % self.getdelimited('[', ']\r', 0)
  739.  
  740.     
  741.     def getatom(self):
  742.         '''Parse an RFC-822 atom.'''
  743.         atomlist = [
  744.             '']
  745.         while self.pos < len(self.field):
  746.             if self.field[self.pos] in self.atomends:
  747.                 break
  748.             else:
  749.                 atomlist.append(self.field[self.pos])
  750.             self.pos = self.pos + 1
  751.         return string.join(atomlist, '')
  752.  
  753.     
  754.     def getphraselist(self):
  755.         '''Parse a sequence of RFC-822 phrases.
  756.         
  757.         A phrase is a sequence of words, which are in turn either
  758.         RFC-822 atoms or quoted-strings.  Phrases are canonicalized
  759.         by squeezing all runs of continuous whitespace into one space.
  760.         '''
  761.         plist = []
  762.         while self.pos < len(self.field):
  763.             if self.field[self.pos] in self.LWS:
  764.                 self.pos = self.pos + 1
  765.             elif self.field[self.pos] == '"':
  766.                 plist.append(self.getquote())
  767.             elif self.field[self.pos] == '(':
  768.                 self.commentlist.append(self.getcomment())
  769.             elif self.field[self.pos] in self.atomends:
  770.                 break
  771.             else:
  772.                 plist.append(self.getatom())
  773.         return plist
  774.  
  775.  
  776.  
  777. class AddressList(AddrlistClass):
  778.     '''An AddressList encapsulates a list of parsed RFC822 addresses.'''
  779.     
  780.     def __init__(self, field):
  781.         AddrlistClass.__init__(self, field)
  782.         if field:
  783.             self.addresslist = self.getaddrlist()
  784.         else:
  785.             self.addresslist = []
  786.  
  787.     
  788.     def __len__(self):
  789.         return len(self.addresslist)
  790.  
  791.     
  792.     def __str__(self):
  793.         return string.joinfields(map(dump_address_pair, self.addresslist), ', ')
  794.  
  795.     
  796.     def __add__(self, other):
  797.         newaddr = AddressList(None)
  798.         newaddr.addresslist = self.addresslist[:]
  799.         for x in other.addresslist:
  800.             pass
  801.         
  802.         return newaddr
  803.  
  804.     
  805.     def __iadd__(self, other):
  806.         for x in other.addresslist:
  807.             pass
  808.         
  809.         return self
  810.  
  811.     
  812.     def __sub__(self, other):
  813.         newaddr = AddressList(None)
  814.         for x in self.addresslist:
  815.             pass
  816.         
  817.         return newaddr
  818.  
  819.     
  820.     def __isub__(self, other):
  821.         for x in other.addresslist:
  822.             pass
  823.         
  824.         return self
  825.  
  826.     
  827.     def __getitem__(self, index):
  828.         return self.addresslist[index]
  829.  
  830.  
  831.  
  832. def dump_address_pair(pair):
  833.     '''Dump a (name, address) pair in a canonicalized form.'''
  834.     if pair[0]:
  835.         return '"' + pair[0] + '" <' + pair[1] + '>'
  836.     else:
  837.         return pair[1]
  838.  
  839. _monthnames = [
  840.     'jan',
  841.     'feb',
  842.     'mar',
  843.     'apr',
  844.     'may',
  845.     'jun',
  846.     'jul',
  847.     'aug',
  848.     'sep',
  849.     'oct',
  850.     'nov',
  851.     'dec',
  852.     'january',
  853.     'february',
  854.     'march',
  855.     'april',
  856.     'may',
  857.     'june',
  858.     'july',
  859.     'august',
  860.     'september',
  861.     'october',
  862.     'november',
  863.     'december']
  864. _daynames = [
  865.     'mon',
  866.     'tue',
  867.     'wed',
  868.     'thu',
  869.     'fri',
  870.     'sat',
  871.     'sun']
  872. _timezones = {
  873.     'UT': 0,
  874.     'UTC': 0,
  875.     'GMT': 0,
  876.     'Z': 0,
  877.     'AST': -400,
  878.     'ADT': -300,
  879.     'EST': -500,
  880.     'EDT': -400,
  881.     'CST': -600,
  882.     'CDT': -500,
  883.     'MST': -700,
  884.     'MDT': -600,
  885.     'PST': -800,
  886.     'PDT': -700 }
  887.  
  888. def parsedate_tz(data):
  889.     '''Convert a date string to a time tuple.
  890.     
  891.     Accounts for military timezones.
  892.     '''
  893.     data = string.split(data)
  894.     if data[0][-1] in (',', '.') or string.lower(data[0]) in _daynames:
  895.         del data[0]
  896.     
  897.     if len(data) == 3:
  898.         stuff = string.split(data[0], '-')
  899.         if len(stuff) == 3:
  900.             data = stuff + data[1:]
  901.         
  902.     
  903.     if len(data) == 4:
  904.         s = data[3]
  905.         i = string.find(s, '+')
  906.         if i > 0:
  907.             data[3:] = [
  908.                 s[:i],
  909.                 s[i + 1:]]
  910.         else:
  911.             data.append('')
  912.     
  913.     if len(data) < 5:
  914.         return None
  915.     
  916.     data = data[:5]
  917.     (dd, mm, yy, tm, tz) = data
  918.     mm = string.lower(mm)
  919.     if not (mm in _monthnames):
  920.         (dd, mm) = (mm, string.lower(dd))
  921.         if not (mm in _monthnames):
  922.             return None
  923.         
  924.     
  925.     mm = _monthnames.index(mm) + 1
  926.     if mm > 12:
  927.         mm = mm - 12
  928.     
  929.     if dd[-1] == ',':
  930.         dd = dd[:-1]
  931.     
  932.     i = string.find(yy, ':')
  933.     if i > 0:
  934.         (yy, tm) = (tm, yy)
  935.     
  936.     if yy[-1] == ',':
  937.         yy = yy[:-1]
  938.     
  939.     if yy[0] not in string.digits:
  940.         (yy, tz) = (tz, yy)
  941.     
  942.     if tm[-1] == ',':
  943.         tm = tm[:-1]
  944.     
  945.     tm = string.splitfields(tm, ':')
  946.     if len(tm) == 2:
  947.         (thh, tmm) = tm
  948.         tss = '0'
  949.     elif len(tm) == 3:
  950.         (thh, tmm, tss) = tm
  951.     else:
  952.         return None
  953.     
  954.     try:
  955.         yy = string.atoi(yy)
  956.         dd = string.atoi(dd)
  957.         thh = string.atoi(thh)
  958.         tmm = string.atoi(tmm)
  959.         tss = string.atoi(tss)
  960.     except string.atoi_error:
  961.         return None
  962.  
  963.     tzoffset = None
  964.     tz = string.upper(tz)
  965.     if _timezones.has_key(tz):
  966.         tzoffset = _timezones[tz]
  967.     else:
  968.         
  969.         try:
  970.             tzoffset = string.atoi(tz)
  971.         except string.atoi_error:
  972.             pass
  973.  
  974.     if tzoffset:
  975.         if tzoffset < 0:
  976.             tzsign = -1
  977.             tzoffset = -tzoffset
  978.         else:
  979.             tzsign = 1
  980.         tzoffset = tzsign * ((tzoffset / 100) * 3600 + (tzoffset % 100) * 60)
  981.     
  982.     tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0, tzoffset)
  983.     return tuple
  984.  
  985.  
  986. def parsedate(data):
  987.     '''Convert a time string to a time tuple.'''
  988.     t = parsedate_tz(data)
  989.     if type(t) == type(()):
  990.         return t[:9]
  991.     else:
  992.         return t
  993.  
  994.  
  995. def mktime_tz(data):
  996.     '''Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.'''
  997.     if data[9] is None:
  998.         return time.mktime(data[:8] + (-1,))
  999.     else:
  1000.         t = time.mktime(data[:8] + (0,))
  1001.         return t - data[9] - time.timezone
  1002.  
  1003.  
  1004. def formatdate(timeval = None):
  1005.     '''Returns time format preferred for Internet standards.
  1006.  
  1007.     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
  1008.     '''
  1009.     if timeval is None:
  1010.         timeval = time.time()
  1011.     
  1012.     return '%s' % time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(timeval))
  1013.  
  1014. if __name__ == '__main__':
  1015.     import sys
  1016.     import os
  1017.     file = os.path.join(os.environ['HOME'], 'Mail/inbox/1')
  1018.     if sys.argv[1:]:
  1019.         file = sys.argv[1]
  1020.     
  1021.     f = open(file, 'r')
  1022.     m = Message(f)
  1023.     print 'From:', m.getaddr('from')
  1024.     print 'To:', m.getaddrlist('to')
  1025.     print 'Subject:', m.getheader('subject')
  1026.     print 'Date:', m.getheader('date')
  1027.     date = m.getdate_tz('date')
  1028.     tz = date[-1]
  1029.     date = time.localtime(mktime_tz(date))
  1030.     if date:
  1031.         print 'ParsedDate:', time.asctime(date),
  1032.         hhmmss = tz
  1033.         (hhmm, ss) = divmod(hhmmss, 60)
  1034.         (hh, mm) = divmod(hhmm, 60)
  1035.         print '%+03d%02d' % (hh, mm),
  1036.         if ss:
  1037.             print '.%02d' % ss,
  1038.         
  1039.         print 
  1040.     else:
  1041.         print 'ParsedDate:', None
  1042.     m.rewindbody()
  1043.     n = 0
  1044.     while f.readline():
  1045.         n = n + 1
  1046.     print 'Lines:', n
  1047.     print '-' * 70
  1048.     print 'len =', len(m)
  1049.     if m.has_key('Date'):
  1050.         print 'Date =', m['Date']
  1051.     
  1052.     if m.has_key('X-Nonsense'):
  1053.         pass
  1054.     
  1055.     print 'keys =', m.keys()
  1056.     print 'values =', m.values()
  1057.     print 'items =', m.items()
  1058.  
  1059.