parser.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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 data := fp.read(8192):
  40. feedparser.feed(data)
  41. return feedparser.close()
  42. def parsestr(self, text, headersonly=False):
  43. """Create a message structure from a string.
  44. Returns the root of the message structure. Optional headersonly is a
  45. flag specifying whether to stop parsing after reading the headers or
  46. not. The default is False, meaning it parses the entire contents of
  47. the file.
  48. """
  49. return self.parse(StringIO(text), headersonly=headersonly)
  50. class HeaderParser(Parser):
  51. def parse(self, fp, headersonly=True):
  52. return Parser.parse(self, fp, True)
  53. def parsestr(self, text, headersonly=True):
  54. return Parser.parsestr(self, text, True)
  55. class BytesParser:
  56. def __init__(self, *args, **kw):
  57. """Parser of binary RFC 2822 and MIME email messages.
  58. Creates an in-memory object tree representing the email message, which
  59. can then be manipulated and turned over to a Generator to return the
  60. textual representation of the message.
  61. The input must be formatted as a block of RFC 2822 headers and header
  62. continuation lines, optionally preceded by a `Unix-from' header. The
  63. header block is terminated either by the end of the input or by a
  64. blank line.
  65. _class is the class to instantiate for new message objects when they
  66. must be created. This class must have a constructor that can take
  67. zero arguments. Default is Message.Message.
  68. """
  69. self.parser = Parser(*args, **kw)
  70. def parse(self, fp, headersonly=False):
  71. """Create a message structure from the data in a binary file.
  72. Reads all the data from the file and returns the root of the message
  73. structure. Optional headersonly is a flag specifying whether to stop
  74. parsing after reading the headers or not. The default is False,
  75. meaning it parses the entire contents of the file.
  76. """
  77. fp = TextIOWrapper(fp, encoding='ascii', errors='surrogateescape')
  78. try:
  79. return self.parser.parse(fp, headersonly)
  80. finally:
  81. fp.detach()
  82. def parsebytes(self, text, headersonly=False):
  83. """Create a message structure from a byte string.
  84. Returns the root of the message structure. Optional headersonly is a
  85. flag specifying whether to stop parsing after reading the headers or
  86. not. The default is False, meaning it parses the entire contents of
  87. the file.
  88. """
  89. text = text.decode('ASCII', errors='surrogateescape')
  90. return self.parser.parsestr(text, headersonly)
  91. class BytesHeaderParser(BytesParser):
  92. def parse(self, fp, headersonly=True):
  93. return BytesParser.parse(self, fp, headersonly=True)
  94. def parsebytes(self, text, headersonly=True):
  95. return BytesParser.parsebytes(self, text, headersonly=True)