home *** CD-ROM | disk | FTP | other *** search
/ Mac-Source 1994 July / Mac-Source_July_1994.iso / Other Langs / python / Lib / rfc822.py < prev    next >
Encoding:
Python Source  |  1994-04-01  |  8.7 KB  |  336 lines  |  [TEXT/R*ch]

  1. # RFC-822 message manipulation class.
  2. #
  3. # XXX This is only a very rough sketch of a full RFC-822 parser;
  4. # in particular the tokenizing of addresses does not adhere to all the
  5. # quoting rules.
  6. #
  7. # Directions for use:
  8. #
  9. # To create a Message object: first open a file, e.g.:
  10. #   fp = open(file, 'r')
  11. # (or use any other legal way of getting an open file object, e.g. use
  12. # sys.stdin or call os.popen()).
  13. # Then pass the open file object to the Message() constructor:
  14. #   m = Message(fp)
  15. #
  16. # To get the text of a particular header there are several methods:
  17. #   str = m.getheader(name)
  18. #   str = m.getrawheader(name)
  19. # where name is the name of the header, e.g. 'Subject'.
  20. # The difference is that getheader() strips the leading and trailing
  21. # whitespace, while getrawheader() doesn't.  Both functions retain
  22. # embedded whitespace (including newlines) exactly as they are
  23. # specified in the header, and leave the case of the text unchanged.
  24. #
  25. # For addresses and address lists there are functions
  26. #   realname, mailaddress = m.getaddr(name) and
  27. #   list = m.getaddrlist(name)
  28. # where the latter returns a list of (realname, mailaddr) tuples.
  29. #
  30. # There is also a method
  31. #   time = m.getdate(name)
  32. # which parses a Date-like field and returns a time-compatible tuple,
  33. # i.e. a tuple such as returned by time.localtime() or accepted by
  34. # time.mktime().
  35. #
  36. # See the class definition for lower level access methods.
  37. #
  38. # There are also some utility functions here.
  39.  
  40.  
  41. import regex
  42. import string
  43. import time
  44.  
  45.  
  46. _monthnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
  47.       'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  48.  
  49.  
  50. class Message:
  51.  
  52.     # Initialize the class instance and read the headers.
  53.     
  54.     def __init__(self, fp):
  55.         self.fp = fp
  56.         #
  57.         try:
  58.             self.startofheaders = self.fp.tell()
  59.         except IOError:
  60.             self.startofheaders = None
  61.         #
  62.         self.readheaders()
  63.         #
  64.         try:
  65.             self.startofbody = self.fp.tell()
  66.         except IOError:
  67.             self.startofbody = None
  68.  
  69.  
  70.     # Rewind the file to the start of the body (if seekable).
  71.  
  72.     def rewindbody(self):
  73.         self.fp.seek(self.startofbody)
  74.  
  75.  
  76.     # Read header lines up to the entirely blank line that
  77.     # terminates them.  The (normally blank) line that ends the
  78.     # headers is skipped, but not included in the returned list.
  79.     # If a non-header line ends the headers, (which is an error),
  80.     # an attempt is made to backspace over it; it is never
  81.     # included in the returned list.
  82.     #
  83.     # The variable self.status is set to the empty string if all
  84.     # went well, otherwise it is an error message.
  85.     # The variable self.headers is a completely uninterpreted list
  86.     # of lines contained in the header (so printing them will
  87.     # reproduce the header exactly as it appears in the file).
  88.  
  89.     def readheaders(self):
  90.         self.headers = list = []
  91.         self.status = ''
  92.         headerseen = 0
  93.         while 1:
  94.             line = self.fp.readline()
  95.             if not line:
  96.                 self.status = 'EOF in headers'
  97.                 break
  98.             if self.islast(line):
  99.                 break
  100.             elif headerseen and line[0] in ' \t':
  101.                 # It's a continuation line.
  102.                 list.append(line)
  103.             elif regex.match('^[!-9;-~]+:', line):
  104.                 # It's a header line.
  105.                 list.append(line)
  106.                 headerseen = 1
  107.             else:
  108.                 # It's not a header line; stop here.
  109.                 if not headerseen:
  110.                     self.status = 'No headers'
  111.                 else:
  112.                     self.status = 'Bad header'
  113.                 # Try to undo the read.
  114.                 try:
  115.                     self.fp.seek(-len(line), 1)
  116.                 except IOError:
  117.                     self.status = \
  118.                         self.status + '; bad seek'
  119.                 break
  120.  
  121.  
  122.     # Method to determine whether a line is a legal end of
  123.     # RFC-822 headers.  You may override this method if your
  124.     # application wants to bend the rules, e.g. to accept lines
  125.     # ending in '\r\n', to strip trailing whitespace, or to
  126.     # recognise MH template separators ('--------'). 
  127.  
  128.     def islast(self, line):
  129.         return line == '\n'
  130.  
  131.  
  132.     # Look through the list of headers and find all lines matching
  133.     # a given header name (and their continuation lines).
  134.     # A list of the lines is returned, without interpretation.
  135.     # If the header does not occur, an empty list is returned.
  136.     # If the header occurs multiple times, all occurrences are
  137.     # returned.  Case is not important in the header name.
  138.  
  139.     def getallmatchingheaders(self, name):
  140.         name = string.lower(name) + ':'
  141.         n = len(name)
  142.         list = []
  143.         hit = 0
  144.         for line in self.headers:
  145.             if string.lower(line[:n]) == name:
  146.                 hit = 1
  147.             elif line[:1] not in string.whitespace:
  148.                 hit = 0
  149.             if hit:
  150.                 list.append(line)
  151.         return list
  152.  
  153.  
  154.     # Similar, but return only the first matching header (and its
  155.     # continuation lines).
  156.  
  157.     def getfirstmatchingheader(self, name):
  158.         name = string.lower(name) + ':'
  159.         n = len(name)
  160.         list = []
  161.         hit = 0
  162.         for line in self.headers:
  163.             if string.lower(line[:n]) == name:
  164.                 hit = 1
  165.             elif line[:1] not in string.whitespace:
  166.                 if hit:
  167.                     break
  168.             if hit:
  169.                 list.append(line)
  170.         return list
  171.  
  172.  
  173.     # A higher-level interface to getfirstmatchingheader().
  174.     # Return a string containing the literal text of the header
  175.     # but with the keyword stripped.  All leading, trailing and
  176.     # embedded whitespace is kept in the string, however.
  177.     # Return None if the header does not occur.
  178.  
  179.     def getrawheader(self, name):
  180.         list = self.getfirstmatchingheader(name)
  181.         if not list:
  182.             return None
  183.         list[0] = list[0][len(name) + 1:]
  184.         return string.joinfields(list, '')
  185.  
  186.  
  187.     # Going one step further: also strip leading and trailing
  188.     # whitespace.
  189.  
  190.     def getheader(self, name):
  191.         text = self.getrawheader(name)
  192.         if text == None:
  193.             return None
  194.         return string.strip(text)
  195.  
  196.  
  197.     # Retrieve a single address from a header as a tuple, e.g.
  198.     # ('Guido van Rossum', 'guido@cwi.nl').
  199.  
  200.     def getaddr(self, name):
  201.         data = self.getheader(name)
  202.         if not data:
  203.             return None, None
  204.         return parseaddr(data)
  205.  
  206.     # Retrieve a list of addresses from a header, where each
  207.     # address is a tuple as returned by getaddr().
  208.  
  209.     def getaddrlist(self, name):
  210.         # XXX This function is not really correct.  The split
  211.         # on ',' might fail in the case of commas within
  212.         # quoted strings.
  213.         data = self.getheader(name)
  214.         if not data:
  215.             return []
  216.         data = string.splitfields(data, ',')
  217.         for i in range(len(data)):
  218.             data[i] = parseaddr(data[i])
  219.         return data
  220.  
  221.     # Retrieve a date field from a header as a tuple compatible
  222.     # with time.mktime().
  223.  
  224.     def getdate(self, name):
  225.         data = self.getheader(name)
  226.         if not data:
  227.             return None
  228.         return parsedate(data)
  229.  
  230.  
  231.  
  232. # Utility functions
  233. # -----------------
  234.  
  235. # XXX Should fix these to be really conformant.
  236. # XXX The inverses of the parse functions may also be useful.
  237.  
  238. # Remove quotes from a string.
  239.  
  240. def unquote(str):
  241.     if len(str) > 1:
  242.         if str[0] == '"' and str[-1:] == '"':
  243.             return str[1:-1]
  244.         if str[0] == '<' and str[-1:] == '>':
  245.             return str[1:-1]
  246.     return str
  247.  
  248. # Parse an address into (name, address) tuple
  249.  
  250. def parseaddr(address):
  251.     # This is probably not perfect
  252.     address = string.strip(address)
  253.     # Case 1: part of the address is in <xx@xx> form.
  254.     pos = regex.search('<.*>', address)
  255.     if pos >= 0:
  256.         name = address[:pos]
  257.         address = address[pos:]
  258.         length = regex.match('<.*>', address)
  259.         name = name + address[length:]
  260.         address = address[:length]
  261.     else:
  262.         # Case 2: part of the address is in (comment) form
  263.         pos = regex.search('(.*)', address)
  264.         if pos >= 0:
  265.             name = address[pos:]
  266.             address = address[:pos]
  267.             length = regex.match('(.*)', name)
  268.             address = address + name[length:]
  269.             name = name[:length]
  270.         else:
  271.             # Case 3: neither. Only an address
  272.             name = ''
  273.     name = string.strip(name)
  274.     address = string.strip(address)
  275.     if address and address[0] == '<' and address[-1] == '>':
  276.         address = address[1:-1]
  277.     if name and name[0] == '(' and name[-1] == ')':
  278.         name = name[1:-1]
  279.     return name, address
  280.  
  281. # Parse a date field
  282.  
  283. def parsedate(data):
  284.     # XXX This completely ignores timezone matters at the moment...
  285.     data = string.split(data)
  286.     if data[0][-1] == ',':
  287.         # There's a dayname here. Skip it
  288.         del data[0]
  289.     if len(data) < 5:
  290.         return None
  291.     data = data[:5]
  292.     [dd, mm, yy, tm, tz] = data
  293.     if not mm in _monthnames:
  294.         return None
  295.     mm = _monthnames.index(mm)+1
  296.     tm = string.splitfields(tm, ':')
  297.     if len(tm) == 2:
  298.         [thh, tmm] = tm
  299.         tss = '0'
  300.     else:
  301.         [thh, tmm, tss] = tm
  302.     try:
  303.         yy = string.atoi(yy)
  304.         dd = string.atoi(dd)
  305.         thh = string.atoi(thh)
  306.         tmm = string.atoi(tmm)
  307.         tss = string.atoi(tss)
  308.     except string.atoi_error:
  309.         return None
  310.     tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0)
  311.     return tuple
  312.  
  313.  
  314. # When used as script, run a small test program.
  315. # The first command line argument must be a filename containing one
  316. # message in RFC-822 format.
  317.  
  318. if __name__ == '__main__':
  319.     import sys
  320.     f = open(sys.argv[1], 'r')
  321.     m = Message(f)
  322.     print 'From:', m.getaddr('from')
  323.     print 'To:', m.getaddrlist('to')
  324.     print 'Subject:', m.getheader('subject')
  325.     print 'Date:', m.getheader('date')
  326.     date = m.getdate('date')
  327.     if date:
  328.         print 'ParsedDate:', time.asctime(date)
  329.     else:
  330.         print 'ParsedDate:', None
  331.     m.rewindbody()
  332.     n = 0
  333.     while f.readline():
  334.         n = n + 1
  335.     print 'Lines:', n
  336.