On 3/18/2023 10:49 PM, Peng Yu wrote:
Hi,

https://docs.python.org/3/library/email.parser.html

It says "For MIME messages, the root object will return True from its
is_multipart() method, and the subparts can be accessed via the
payload manipulation methods, such as get_body(), iter_parts(), and
walk()."

But when I try the following code, get_body() is not found. How to get
get_body() to work?

$ python3 -c 'import email, sys; msg =
email.message_from_string(sys.stdin.read()); print(msg.get_body())'
<<< some_text
Traceback (most recent call last):
   File "<string>", line 1, in <module>
AttributeError: 'Message' object has no attribute 'get_body'

A Message object does not have a get_body method, but an EmailMessage object does.

In the Python 3.10 docs, Just before the part you quoted, there is this sentence:

"You can pass the parser a bytes, string or file object, and the parser will return to you the root EmailMessage instance of the object structure".

So if you want to use get_body(), you should be feeding the parser your message string, rather than using email.message_from_string(), which returns a Message, not an EmailMessage.

With a Message object, you could use get_payload(), which will give you a list of Messages for each MIME part of the document. When a part is not a multipart, it will give you a string, which sounds like what you want to end up with.

(see https://docs.python.org/3.10/library/email.compat32-message.html)
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to