Search code examples
pythonpython-3.xmimemime-message

'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'] = 'me@example.com'
message['from'] = 'you@example.com'
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: me@example.com
from: you@example.com
subject: test subject

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

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

Solution

  • 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: me@example.com
    from: you@example.com
    subject: test subject
    
    this is a test body
    

    Give this a try:

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