1

Hello there I trying to read my email and code is :

FROM_EMAIL  = "emailadd"
FROM_PWD    = "pasword"
SMTP_SERVER = "imapaddress"
SMTP_PORT   = 111

mail = imaplib.IMAP4_SSL(SMTP_SERVER)

mail.login(FROM_EMAIL,FROM_PWD)

mail.select('inbox')


type,data = mail.search(None, '(SUBJECT "IP")')
msgList = data[0].split()
last=msgList[len(msgList)-1]
type1,data1 = mail.fetch(last, '(RFC822)')
msg=email.message_from_string(data1[0][1])
content = msg.get_payload(decode=True)


mail.close()
mail.logout()

when I print content it will give me back as None but my email has body text anyone can help me ?

robinshion
  • 33
  • 1
  • 7

2 Answers2

4

From the documentation,

If the message is a multipart and the decode flag is True, then None is returned.

Moral: Don't set the decode flag when you fetch multipart messages.

If you are going to parse multipart messages, you might become familiar with the relevant RFC. Meanwhile, this quick-and-dirty might get you the data you need:

msg=email.message_from_string(data1[0][1])

# If we have a (nested) multipart message, try to get
# past all of the potatoes and straight to the meat
# For production, you might want a more thought-out
# approach, but maybe just fetching the first item
# will be sufficient for your needs
while msg.is_multipart():
    msg = msg.get_payload(0)

content = msg.get_payload(decode=True)
Community
  • 1
  • 1
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Thanks reply, I tried use str(msg) I read as Content-Type: text/plain; charset="us-ascii", and I took the decode out but it gives me back as :[, ] – robinshion Feb 23 '18 at 21:25
  • Yes, `.get_payload()` of a multipart message returns a list. From the same documentation, msg "*will be a list of `Message` objects when `is_multipart()` is `True`*". – Robᵩ Feb 23 '18 at 22:26
1

Building on Rob's answer, here is slightly more sophisticated code:

msg=email.message_from_string(data1[0][1])
if msg.is_multipart():
    for part in email_message.walk():
        ctype = part.get_content_maintype()
        cdispo = str(part.get('Content-Disposition'))

        # skip any text/plain (txt) attachments
        if ctype == 'text' and 'attachment' not in cdispo:
            body = part.get_payload(decode=True)  # decode
            break
# not multipart - plain text
else:
    body = msg.get_payload(decode=True)

This code is mainly taken from this answer.

Peter K
  • 1,959
  • 1
  • 16
  • 22