' MimeText用于'对象没有属性'编码'

时间:2018-05-06 14:03:42

标签: python python-3.x mime mime-message

您好我正在努力解决为什么我收到此错误。它让我有点困惑。我使用的是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('---------------')

这是输出。

++++++++++++++++++++++++++++++++++
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'
---------------

1 个答案:

答案 0 :(得分:1)

MIMEText没有.encode()方法,看起来你想要as_string()方法。

message.as_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

尝试一下:

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