IMAP get sender name and body text?

前端 未结 2 1102
遇见更好的自我
遇见更好的自我 2021-01-12 01:30

I am using this code:

import imaplib
mail = imaplib.IMAP4_SSL(\'imap.gmail.com\')
mail.login(myusername, mypassword)
mail.list()
# Out: list of \"folders\" a         


        
相关标签:
2条回答
  • 2021-01-12 01:57

    Python's email package is probably a good place to start.

    import email
    msg = email.message_from_string(raw_email)
    
    print msg['From']
    print msg.get_payload(decode=True)
    

    That should do ask you ask, though when an email has multiple parts (attachments, text and HTML versions of the body, etc.) things are a bit more complicated.

    In that case, msg.is_multipart() will return True and msg.get_payload() will return a list instead of a string. There's a lot more information in the email.message documentation.

    Alternately, rather than parsing the raw RFC822-formatted message - which could be very large, if the email contains attachments - you could just ask the IMAP server for the information you want. Changing your mail.fetch line to:

    mail.fetch(latest_email_id, "(BODY[HEADER.FIELDS (FROM)])")
    

    Would just request (and return) the From line of the email from the server. Likewise setting the second parameter to "(UID BODY[TEXT])" would return the body of the email. RFC2060 has a list of parameters that should be valid here.

    0 讨论(0)
  • 2021-01-12 02:08
    from imap_tools import MailBox, A
    with MailBox('imap.mail.com').login('test@mail.com', 'password', 'INBOX') as mailbox:
        for msg in mailbox.fetch(A(all=True)):
            sender = msg.from_
            body = msg.text or msg.html
    

    IMAP high level lib: https://github.com/ikvk/imap_tools (I am author)

    0 讨论(0)
提交回复
热议问题