Python pull back plain text body from message from IMAP account

前端 未结 2 1477
忘掉有多难
忘掉有多难 2021-01-24 18:39

I have been working on this and am missing the mark.

I am able to connect and get the mail via imaplib.

msrv = imaplib.IMAP4(server)
msrv.login(username,         


        
相关标签:
2条回答
  • 2021-01-24 19:40

    To get the plain text version of the body of the email I did something like this....

    xxx= data[0][1] #puts message from list into string
    
    
    xyz=email.message_from_string(xxx)# converts string to instance of message xyz is an email message so multipart and walk work on it.
    
    #Finds the plain text version of the body of the message.
    
    if xyz.get_content_maintype() == 'multipart': #If message is multi part we only want the text version of the body, this walks the message and gets the body.
        for part in xyz.walk():       
            if part.get_content_type() == "text/plain":
                body = part.get_payload(decode=True)
            else:
                        continue
    
    0 讨论(0)
  • 2021-01-24 19:40

    Here is a minimal example from the docs:

    import getpass, imaplib
    
    M = imaplib.IMAP4()
    M.login(getpass.getuser(), getpass.getpass())
    M.select()
    typ, data = M.search(None, 'ALL')
    for num in data[0].split():
        typ, data = M.fetch(num, '(RFC822)')
        print 'Message %s\n%s\n' % (num, data[0][1])
    M.close()
    M.logout()
    

    In this case, data[0][1] contains the message body.

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