问题
When reading emails from a specific folder (Office365), the body of the message is a random long string that makes no sense.
Initially, I sent those emails to my personal mail as copy, to a specific folder. Reading from there I haven't had problems. But when I try to read directly from the main inbox, the messages are long strings that makes no sense (so, I can´t parse anything)
mail = imaplib.IMAP4_SSL(SMTP_SERVER)
mail.login(FROM_EMAIL, FROM_PWD)
boxes = mail.list()
mail.select('INBOX/netstatus', readonly=True)
(type, data) = mail.uid('SEARCH', None, '(UNSEEN)')
mail_ids = data[0]
id_list = mail_ids.split()
def read_email(self, *id_list):
id_list = list(id_list)
for i in reversed(id_list):
(typ, data) = mail.uid('FETCH', i, '(RFC822)')
for response_part in data:
if isinstance(response_part, tuple):
print("Response: ",response_part)
msg = \ email.message_from_string(response_part[1].decode('utf-8'))
body = ''
email_subject = msg['subject']
email_from = msg['from']
email_date = msg['date']
message= msg.get_payload().encode('utf-8')
print(message)
I receive something like this when I read from my personal inbox:
mymail: b'Status from Device (x.x.x.x) to AnotherDevice (y.y.y.y), interface A B, in Protocol came up\r\n'
But when I read from the main inbox:
'QWRq4N5IGZyb20gVVREFxLXJlMSAuMTAuMjUsIDAxMDAuMTAwMS4w\r\nMDI1LjAwKSB0byBVU0FEQUxIERS4MC4xMC4xMMDAxLjAw\r\nMjUuMDQpLCBpbnZhY2UgMTAuMTA4AuMjI5IHRvIDEwLjEwLjIwLjEzMCwgaW4gSVNJUy9M\r\nZXZlbDIgd2VudCBkkNvbmZ3VyZWQgd2F0Y2hsaXN0OiI1OQ0K\r\n'
回答1:
With Python3.6 or later, you can use EmailMessage.get_content() to decode the encoded content automatically.
import email
from email import policy
# Email based on one of the examples at https://docs.python.org/3.6/library/email.examples.html
s = """
Subject: Ayons asperges pour le =?utf-8?q?d=C3=A9jeuner?=
From: =?utf-8?q?Pep=C3=A9?= Le Pew <pepe@example.com>
To: Penelope Pussycat <penelope@example.com>,
Fabrette Pussycat <fabrette@example.com>
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: base64
MIME-Version: 1.0
ICAgIFNhbHV0IQoKICAgIENlbGEgcmVzc2VtYmxlIMOgIHVuIGV4Y2VsbGVudCByZWNpcGllWzFd
IGTDqWpldW5lci4KCiAgICBbMV0gaHR0cDovL3d3dy55dW1tbHkuY29tL3JlY2lwZS9Sb2FzdGVk
LUFzcGFyYWd1cy1FcGljdXJpb3VzLTIwMzcxOAoKICAgIC0tUGVww6kKICAgIAo=
"""
msg = email.message_from_string(s, policy=policy.default)
print(msg.get_content())
Salut!
Cela ressemble à un excellent recipie[1] déjeuner.
[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718
--Pepé
For multipart messages you need to iterate over the parts:
for part in msg.iter_parts():
print(part.get_content())
来源:https://stackoverflow.com/questions/53877899/errors-receiving-emails-with-imaplib-from-a-specific-inbox