Extract To header: from email attachment

I am using python to open email on the server (POP3). Each email has an attachment that is a redirected email address.

I need to get the address "To:" from the attachment.

I use python to try to help me learn the language, and I'm not so good yet!

The code that I already have is

import poplib, email, mimetypes

    oPop = poplib.POP3( 'xx.xxx.xx.xx' )
    oPop.user( 'abc@xxxxx.xxx' )
    oPop.pass_( 'xxxxxx' )

    (iNumMessages, iTotalSize ) = oPop.stat()

    for thisNum in range(1, iNumMessages + 1): 
          (server_msg, body, octets) = oPop.retr(thisNum)
          sMail = "\n".join( body )

          oMsg = email.message_from_string( sMail )

          # now what ?? 

I understand that I have an email as an instance of the email class, but I'm not sure how to get to the attachment

I know that using

  sData = 'To'
       if sData in oMsg:
       print sData + "", oMsg[sData]

gets the “To:” header from the main message, but how do I get it from the attachment?

I tried

for part in oMsg.walk():
    oAttach = part.get_payload(1)

But I'm not sure what to do with the oAttach object. I tried turning it into a string and then passing it to

oMsgAttach = email.message_from_string( oAttach )

. python . .

+3
1

, , ( poplib). , , :

, python dir() help(): , . help(oAttach), dir(oAttach) print oAttach , , , . , .

, , . , , base64, - :

#!/usr/bin/python
import poplib, email, mimetypes

# Do everything you've done in the first code block of your question
# ...
# ...

import base64
for part in oMsg.walk():
    # I've removed the '1' from the argument as I think you always get the
    # the first entry (in my test, it was the third iteration that did it).
    # However, I could be wrong...
    oAttach = part.get_payload()
    # Decode the base64 encoded attachment
    oContent = b64decode(oAttach)
    # then maybe...?
    oMsgAttach = email.message_from_string(oContent)

, , , oAttach , , . sMail, . - Content-Transfer-Encoding: base64, .

, poplib, email mimetypes, , , , .

+1

Source: https://habr.com/ru/post/1715625/


All Articles