home *** CD-ROM | disk | FTP | other *** search
/ Enter 2004 (Extra) / ENTER.ISO / files / OO / f_0379 / python-core-2.2.2 / lib / email / Parser.py < prev    next >
Encoding:
Python Source  |  2004-03-27  |  11.6 KB  |  276 lines

  1. # Copyright (C) 2001,2002 Python Software Foundation
  2. # Author: barry@zope.com (Barry Warsaw)
  3.  
  4. """A parser of RFC 2822 and MIME email messages.
  5. """
  6.  
  7. import re
  8. from cStringIO import StringIO
  9. from types import ListType
  10.  
  11. from email import Errors
  12. from email import Message
  13.  
  14. EMPTYSTRING = ''
  15. NL = '\n'
  16.  
  17. try:
  18.     True, False
  19. except NameError:
  20.     True = 1
  21.     False = 0
  22.  
  23. nlcre = re.compile('\r\n|\r|\n')
  24.  
  25.  
  26.  
  27. class Parser:
  28.     def __init__(self, _class=Message.Message, strict=False):
  29.         """Parser of RFC 2822 and MIME email messages.
  30.  
  31.         Creates an in-memory object tree representing the email message, which
  32.         can then be manipulated and turned over to a Generator to return the
  33.         textual representation of the message.
  34.  
  35.         The string must be formatted as a block of RFC 2822 headers and header
  36.         continuation lines, optionally preceeded by a `Unix-from' header.  The
  37.         header block is terminated either by the end of the string or by a
  38.         blank line.
  39.  
  40.         _class is the class to instantiate for new message objects when they
  41.         must be created.  This class must have a constructor that can take
  42.         zero arguments.  Default is Message.Message.
  43.  
  44.         Optional strict tells the parser to be strictly RFC compliant or to be
  45.         more forgiving in parsing of ill-formatted MIME documents.  When
  46.         non-strict mode is used, the parser will try to make up for missing or
  47.         erroneous boundaries and other peculiarities seen in the wild.
  48.         Default is non-strict parsing.
  49.         """
  50.         self._class = _class
  51.         self._strict = strict
  52.  
  53.     def parse(self, fp, headersonly=False):
  54.         """Create a message structure from the data in a file.
  55.  
  56.         Reads all the data from the file and returns the root of the message
  57.         structure.  Optional headersonly is a flag specifying whether to stop
  58.         parsing after reading the headers or not.  The default is False,
  59.         meaning it parses the entire contents of the file.
  60.         """
  61.         root = self._class()
  62.         self._parseheaders(root, fp)
  63.         if not headersonly:
  64.             self._parsebody(root, fp)
  65.         return root
  66.  
  67.     def parsestr(self, text, headersonly=False):
  68.         """Create a message structure from a string.
  69.  
  70.         Returns the root of the message structure.  Optional headersonly is a
  71.         flag specifying whether to stop parsing after reading the headers or
  72.         not.  The default is False, meaning it parses the entire contents of
  73.         the file.
  74.         """
  75.         return self.parse(StringIO(text), headersonly=headersonly)
  76.  
  77.     def _parseheaders(self, container, fp):
  78.         # Parse the headers, returning a list of header/value pairs.  None as
  79.         # the header means the Unix-From header.
  80.         lastheader = ''
  81.         lastvalue = []
  82.         lineno = 0
  83.         while True:
  84.             # Don't strip the line before we test for the end condition,
  85.             # because whitespace-only header lines are RFC compliant
  86.             # continuation lines.
  87.             line = fp.readline()
  88.             if not line:
  89.                 break
  90.             line = line.splitlines()[0]
  91.             if not line:
  92.                 break
  93.             # Ignore the trailing newline
  94.             lineno += 1
  95.             # Check for initial Unix From_ line
  96.             if line.startswith('From '):
  97.                 if lineno == 1:
  98.                     container.set_unixfrom(line)
  99.                     continue
  100.                 elif self._strict:
  101.                     raise Errors.HeaderParseError(
  102.                         'Unix-from in headers after first rfc822 header')
  103.                 else:
  104.                     # ignore the wierdly placed From_ line
  105.                     # XXX: maybe set unixfrom anyway? or only if not already?
  106.                     continue
  107.             # Header continuation line
  108.             if line[0] in ' \t':
  109.                 if not lastheader:
  110.                     raise Errors.HeaderParseError(
  111.                         'Continuation line seen before first header')
  112.                 lastvalue.append(line)
  113.                 continue
  114.             # Normal, non-continuation header.  BAW: this should check to make
  115.             # sure it's a legal header, e.g. doesn't contain spaces.  Also, we
  116.             # should expose the header matching algorithm in the API, and
  117.             # allow for a non-strict parsing mode (that ignores the line
  118.             # instead of raising the exception).
  119.             i = line.find(':')
  120.             if i < 0:
  121.                 if self._strict:
  122.                     raise Errors.HeaderParseError(
  123.                         "Not a header, not a continuation: ``%s''"%line)
  124.                 elif lineno == 1 and line.startswith('--'):
  125.                     # allow through duplicate boundary tags.
  126.                     continue
  127.                 else:
  128.                     raise Errors.HeaderParseError(
  129.                         "Not a header, not a continuation: ``%s''"%line)
  130.             if lastheader:
  131.                 container[lastheader] = NL.join(lastvalue)
  132.             lastheader = line[:i]
  133.             lastvalue = [line[i+1:].lstrip()]
  134.         # Make sure we retain the last header
  135.         if lastheader:
  136.             container[lastheader] = NL.join(lastvalue)
  137.  
  138.     def _parsebody(self, container, fp):
  139.         # Parse the body, but first split the payload on the content-type
  140.         # boundary if present.
  141.         boundary = container.get_boundary()
  142.         isdigest = (container.get_content_type() == 'multipart/digest')
  143.         # If there's a boundary, split the payload text into its constituent
  144.         # parts and parse each separately.  Otherwise, just parse the rest of
  145.         # the body as a single message.  Note: any exceptions raised in the
  146.         # recursive parse need to have their line numbers coerced.
  147.         if boundary:
  148.             preamble = epilogue = None
  149.             # Split into subparts.  The first boundary we're looking for won't
  150.             # always have a leading newline since we're at the start of the
  151.             # body text, and there's not always a preamble before the first
  152.             # boundary.
  153.             separator = '--' + boundary
  154.             payload = fp.read()
  155.             # We use an RE here because boundaries can have trailing
  156.             # whitespace.
  157.             mo = re.search(
  158.                 r'(?P<sep>' + re.escape(separator) + r')(?P<ws>[ \t]*)',
  159.                 payload)
  160.             if not mo:
  161.                 if self._strict:
  162.                     raise Errors.BoundaryError(
  163.                         "Couldn't find starting boundary: %s" % boundary)
  164.                 container.set_payload(payload)
  165.                 return
  166.             start = mo.start()
  167.             if start > 0:
  168.                 # there's some pre-MIME boundary preamble
  169.                 preamble = payload[0:start]
  170.             # Find out what kind of line endings we're using
  171.             start += len(mo.group('sep')) + len(mo.group('ws'))
  172.             mo = nlcre.search(payload, start)
  173.             if mo:
  174.                 start += len(mo.group(0))
  175.             # We create a compiled regexp first because we need to be able to
  176.             # specify the start position, and the module function doesn't
  177.             # support this signature. :(
  178.             cre = re.compile('(?P<sep>\r\n|\r|\n)' +
  179.                              re.escape(separator) + '--')
  180.             mo = cre.search(payload, start)
  181.             if mo:
  182.                 terminator = mo.start()
  183.                 linesep = mo.group('sep')
  184.                 if mo.end() < len(payload):
  185.                     # There's some post-MIME boundary epilogue
  186.                     epilogue = payload[mo.end():]
  187.             elif self._strict:
  188.                 raise Errors.BoundaryError(
  189.                         "Couldn't find terminating boundary: %s" % boundary)
  190.             else:
  191.                 # Handle the case of no trailing boundary.  Check that it ends
  192.                 # in a blank line.  Some cases (spamspamspam) don't even have
  193.                 # that!
  194.                 mo = re.search('(?P<sep>\r\n|\r|\n){2}$', payload)
  195.                 if not mo:
  196.                     mo = re.search('(?P<sep>\r\n|\r|\n)$', payload)
  197.                     if not mo:
  198.                         raise Errors.BoundaryError(
  199.                           'No terminating boundary and no trailing empty line')
  200.                 linesep = mo.group('sep')
  201.                 terminator = len(payload)
  202.             # We split the textual payload on the boundary separator, which
  203.             # includes the trailing newline. If the container is a
  204.             # multipart/digest then the subparts are by default message/rfc822
  205.             # instead of text/plain.  In that case, they'll have a optional
  206.             # block of MIME headers, then an empty line followed by the
  207.             # message headers.
  208.             parts = re.split(
  209.                 linesep + re.escape(separator) + r'[ \t]*' + linesep,
  210.                 payload[start:terminator])
  211.             for part in parts:
  212.                 if isdigest:
  213.                     if part.startswith(linesep):
  214.                         # There's no header block so create an empty message
  215.                         # object as the container, and lop off the newline so
  216.                         # we can parse the sub-subobject
  217.                         msgobj = self._class()
  218.                         part = part[len(linesep):]
  219.                     else:
  220.                         parthdrs, part = part.split(linesep+linesep, 1)
  221.                         # msgobj in this case is the "message/rfc822" container
  222.                         msgobj = self.parsestr(parthdrs, headersonly=1)
  223.                     # while submsgobj is the message itself
  224.                     submsgobj = self.parsestr(part)
  225.                     msgobj.attach(submsgobj)
  226.                     msgobj.set_default_type('message/rfc822')
  227.                 else:
  228.                     msgobj = self.parsestr(part)
  229.                 container.preamble = preamble
  230.                 container.epilogue = epilogue
  231.                 container.attach(msgobj)
  232.         elif container.get_main_type() == 'multipart':
  233.             # Very bad.  A message is a multipart with no boundary!
  234.             raise Errors.BoundaryError(
  235.                 'multipart message with no defined boundary')
  236.         elif container.get_type() == 'message/delivery-status':
  237.             # This special kind of type contains blocks of headers separated
  238.             # by a blank line.  We'll represent each header block as a
  239.             # separate Message object
  240.             blocks = []
  241.             while True:
  242.                 blockmsg = self._class()
  243.                 self._parseheaders(blockmsg, fp)
  244.                 if not len(blockmsg):
  245.                     # No more header blocks left
  246.                     break
  247.                 blocks.append(blockmsg)
  248.             container.set_payload(blocks)
  249.         elif container.get_main_type() == 'message':
  250.             # Create a container for the payload, but watch out for there not
  251.             # being any headers left
  252.             try:
  253.                 msg = self.parse(fp)
  254.             except Errors.HeaderParseError:
  255.                 msg = self._class()
  256.                 self._parsebody(msg, fp)
  257.             container.attach(msg)
  258.         else:
  259.             container.set_payload(fp.read())
  260.  
  261.  
  262.  
  263. class HeaderParser(Parser):
  264.     """A subclass of Parser, this one only meaningfully parses message headers.
  265.  
  266.     This class can be used if all you're interested in is the headers of a
  267.     message.  While it consumes the message body, it does not parse it, but
  268.     simply makes it available as a string payload.
  269.  
  270.     Parsing with this subclass can be considerably faster if all you're
  271.     interested in is the message headers.
  272.     """
  273.     def _parsebody(self, container, fp):
  274.         # Consume but do not parse, the body
  275.         container.set_payload(fp.read())
  276.