blob: 479928ec945d77f092879deb4d70392fa4091f93 [file] [log] [blame]
Guido van Rossum8b3febe2007-08-30 01:15:14 +00001# Copyright (C) 2001-2006 Python Software Foundation
2# Author: Barry Warsaw
3# Contact: email-sig@python.org
4
5"""Class representing text/* type MIME documents."""
6
7__all__ = ['MIMEText']
8
Berker Peksagfe21e4d2014-09-27 00:57:29 +03009from email.charset import Charset
Guido van Rossum8b3febe2007-08-30 01:15:14 +000010from email.mime.nonmultipart import MIMENonMultipart
11
12
13
14class MIMEText(MIMENonMultipart):
15 """Class for generating text/* type MIME documents."""
16
R David Murray42243c42012-03-22 22:40:44 -040017 def __init__(self, _text, _subtype='plain', _charset=None):
Guido van Rossum8b3febe2007-08-30 01:15:14 +000018 """Create a text/* type MIME document.
19
20 _text is the string for this message object.
21
22 _subtype is the MIME sub content type, defaulting to "plain".
23
24 _charset is the character set parameter added to the Content-Type
25 header. This defaults to "us-ascii". Note that as a side-effect, the
26 Content-Transfer-Encoding header will also be set.
27 """
R David Murray8680bcc2012-03-22 22:17:51 -040028
Terry Jan Reedy0f847642013-03-11 18:34:00 -040029 # If no _charset was specified, check to see if there are non-ascii
R David Murray42243c42012-03-22 22:40:44 -040030 # characters present. If not, use 'us-ascii', otherwise use utf-8.
R David Murray8680bcc2012-03-22 22:17:51 -040031 # XXX: This can be removed once #7304 is fixed.
R David Murray42243c42012-03-22 22:40:44 -040032 if _charset is None:
R David Murray8680bcc2012-03-22 22:17:51 -040033 try:
R David Murray42243c42012-03-22 22:40:44 -040034 _text.encode('us-ascii')
35 _charset = 'us-ascii'
R David Murray8680bcc2012-03-22 22:17:51 -040036 except UnicodeEncodeError:
37 _charset = 'utf-8'
Berker Peksagfe21e4d2014-09-27 00:57:29 +030038 if isinstance(_charset, Charset):
39 _charset = str(_charset)
R David Murray8680bcc2012-03-22 22:17:51 -040040
R David Murray42243c42012-03-22 22:40:44 -040041 MIMENonMultipart.__init__(self, 'text', _subtype,
42 **{'charset': _charset})
43
Guido van Rossum8b3febe2007-08-30 01:15:14 +000044 self.set_payload(_text, _charset)