text.py 1.5 KB

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