【问题标题】:'MIMEText' object has no attribute 'encode''MIMEText' 对象没有属性 'encode'
【发布时间】:2018-10-16 10:52:42
【问题描述】:

您好,我正在尝试找出我收到此错误的原因。它让我有点困惑。我正在使用 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'
---------------

【问题讨论】:

  • 我不知道 MIMEText,但显然您的 MIMEText 不是字符串,因此您需要检查文档以了解如何获取内部字符串并将编码然后应用于字符串.

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


【解决方案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')

【讨论】:

    猜你喜欢
    • 2019-10-18
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2015-03-28
    • 2021-04-23
    相关资源
    最近更新 更多