text.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Copyright (C) 2001-2006 Python Software Foundation
  2. # Author: Barry Warsaw
  3. # Contact: email-sig@python.org
  4. """Class representing text/* type MIME documents."""
  5. __all__ = ['MIMEText']
  6. from email.charset import Charset
  7. from email.mime.nonmultipart import MIMENonMultipart
  8. class MIMEText(MIMENonMultipart):
  9. """Class for generating text/* type MIME documents."""
  10. def __init__(self, _text, _subtype='plain', _charset=None, *, policy=None):
  11. """Create a text/* type MIME document.
  12. _text is the string for this message object.
  13. _subtype is the MIME sub content type, defaulting to "plain".
  14. _charset is the character set parameter added to the Content-Type
  15. header. This defaults to "us-ascii". Note that as a side-effect, the
  16. Content-Transfer-Encoding header will also be set.
  17. """
  18. # If no _charset was specified, check to see if there are non-ascii
  19. # characters present. If not, use 'us-ascii', otherwise use utf-8.
  20. # XXX: This can be removed once #7304 is fixed.
  21. if _charset is None:
  22. try:
  23. _text.encode('us-ascii')
  24. _charset = 'us-ascii'
  25. except UnicodeEncodeError:
  26. _charset = 'utf-8'
  27. MIMENonMultipart.__init__(self, 'text', _subtype, policy=policy,
  28. **{'charset': str(_charset)})
  29. self.set_payload(_text, _charset)