user1768233
user1768233

Reputation: 1461

'MIMEText' object has no attribute 'encode'

Hi I am trying to work out why I am getting this error. Its got me a little baffled. I am using Python 3.6

logger = logging.getLogger(__name__)
message_text = 'this is a test body'
message = MIMEText(message_text)
message['to'] = '[email protected]'
message['from'] = '[email protected]'
message['subject'] = 'test subject'
logger.debug('++++++++++++++++++++++++++++++++++')
logger.debug(message)
logger.debug('++++++++++++++++++++++++++++++++++')
try:
  raw = base64.urlsafe_b64encode(message.encode('UTF-8')).decode('ascii')
except Exception as e:
  logger.debug('---------------')
  logger.debug(e)
  logger.debug('---------------')

And this is the output.

++++++++++++++++++++++++++++++++++
Content-Type: text/plain; charset="us-ascii". 
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit.  
to: [email protected]
from: [email protected]
subject: test subject

this is a test body
++++++++++++++++++++++++++++++++++

---------------
'MIMEText' object has no attribute 'encode'
---------------

Upvotes: 2

Views: 9046

Answers (1)

ktzr
ktzr

Reputation: 1645

MIMEText does not have an .encode() method, it looks like you want the as_string() method.

message.as_string() will return the following string:

Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
to: [email protected]
from: [email protected]
subject: test subject

this is a test body

Give this a try:

raw = base64.urlsafe_b64encode(message.as_string().encode('UTF-8')).decode('ascii')

Upvotes: 2

Related Questions