text.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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.mime.nonmultipart import MIMENonMultipart
  7. class MIMEText(MIMENonMultipart):
  8. """Class for generating text/* type MIME documents."""
  9. def __init__(self, _text, _subtype='plain', _charset=None, *, policy=None):
  10. """Create a text/* type MIME document.
  11. _text is the string for this message object.
  12. _subtype is the MIME sub content type, defaulting to "plain".
  13. _charset is the character set parameter added to the Content-Type
  14. header. This defaults to "us-ascii". Note that as a side-effect, the
  15. Content-Transfer-Encoding header will also be set.
  16. """
  17. # If no _charset was specified, check to see if there are non-ascii
  18. # characters present. If not, use 'us-ascii', otherwise use utf-8.
  19. # XXX: This can be removed once #7304 is fixed.
  20. if _charset is None:
  21. try:
  22. _text.encode('us-ascii')
  23. _charset = 'us-ascii'
  24. except UnicodeEncodeError:
  25. _charset = 'utf-8'
  26. MIMENonMultipart.__init__(self, 'text', _subtype, policy=policy,
  27. charset=str(_charset))
  28. self.set_payload(_text, _charset)