parser.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. # Copyright (C) 2001-2007 Python Software Foundation
  2. # Author: Barry Warsaw, Thomas Wouters, Anthony Baxter
  3. # Contact: email-sig@python.org
  4. """A parser of RFC 2822 and MIME email messages."""
  5. __all__ = ['Parser', 'HeaderParser', 'BytesParser', 'BytesHeaderParser',
  6. 'FeedParser', 'BytesFeedParser']
  7. from io import StringIO, TextIOWrapper
  8. from email.feedparser import FeedParser, BytesFeedParser
  9. from email._policybase import compat32
  10. class Parser:
  11. def __init__(self, _class=None, *, policy=compat32):
  12. """Parser of RFC 2822 and MIME email messages.
  13. Creates an in-memory object tree representing the email message, which
  14. can then be manipulated and turned over to a Generator to return the
  15. textual representation of the message.
  16. The string must be formatted as a block of RFC 2822 headers and header
  17. continuation lines, optionally preceded by a `Unix-from' header. The
  18. header block is terminated either by the end of the string or by a
  19. blank line.
  20. _class is the class to instantiate for new message objects when they
  21. must be created. This class must have a constructor that can take
  22. zero arguments. Default is Message.Message.
  23. The policy keyword specifies a policy object that controls a number of
  24. aspects of the parser's operation. The default policy maintains
  25. backward compatibility.
  26. """
  27. self._class = _class
  28. self.policy = policy
  29. def parse(self, fp, headersonly=False):
  30. """Create a message structure from the data in a file.
  31. Reads all the data from the file and returns the root of the message
  32. structure. Optional headersonly is a flag specifying whether to stop
  33. parsing after reading the headers or not. The default is False,
  34. meaning it parses the entire contents of the file.
  35. """
  36. feedparser = FeedParser(self._class, policy=self.policy)
  37. if headersonly:
  38. feedparser._set_headersonly()
  39. while True:
  40. data = fp.read(8192)
  41. if not data:
  42. break
  43. feedparser.feed(data)
  44. return feedparser.close()
  45. def parsestr(self, text, headersonly=False):
  46. """Create a message structure from a string.
  47. Returns the root of the message structure. Optional headersonly is a
  48. flag specifying whether to stop parsing after reading the headers or
  49. not. The default is False, meaning it parses the entire contents of
  50. the file.
  51. """
  52. return self.parse(StringIO(text), headersonly=headersonly)
  53. class HeaderParser(Parser):
  54. def parse(self, fp, headersonly=True):
  55. return Parser.parse(self, fp, True)
  56. def parsestr(self, text, headersonly=True):
  57. return Parser.parsestr(self, text, True)
  58. class BytesParser:
  59. def __init__(self, *args, **kw):
  60. """Parser of binary RFC 2822 and MIME email messages.
  61. Creates an in-memory object tree representing the email message, which
  62. can then be manipulated and turned over to a Generator to return the
  63. textual representation of the message.
  64. The input must be formatted as a block of RFC 2822 headers and header
  65. continuation lines, optionally preceded by a `Unix-from' header. The
  66. header block is terminated either by the end of the input or by a
  67. blank line.
  68. _class is the class to instantiate for new message objects when they
  69. must be created. This class must have a constructor that can take
  70. zero arguments. Default is Message.Message.
  71. """
  72. self.parser = Parser(*args, **kw)
  73. def parse(self, fp, headersonly=False):
  74. """Create a message structure from the data in a binary file.
  75. Reads all the data from the file and returns the root of the message
  76. structure. Optional headersonly is a flag specifying whether to stop
  77. parsing after reading the headers or not. The default is False,
  78. meaning it parses the entire contents of the file.
  79. """
  80. fp = TextIOWrapper(fp, encoding='ascii', errors='surrogateescape')
  81. try:
  82. return self.parser.parse(fp, headersonly)
  83. finally:
  84. fp.detach()
  85. def parsebytes(self, text, headersonly=False):
  86. """Create a message structure from a byte string.
  87. Returns the root of the message structure. Optional headersonly is a
  88. flag specifying whether to stop parsing after reading the headers or
  89. not. The default is False, meaning it parses the entire contents of
  90. the file.
  91. """
  92. text = text.decode('ASCII', errors='surrogateescape')
  93. return self.parser.parsestr(text, headersonly)
  94. class BytesHeaderParser(BytesParser):
  95. def parse(self, fp, headersonly=True):
  96. return BytesParser.parse(self, fp, headersonly=True)
  97. def parsebytes(self, text, headersonly=True):
  98. return BytesParser.parsebytes(self, text, headersonly=True)