Search code examples
pythonbase64pop3poplib

python poplib.POP3 decrypt base64


I'm trying to download all emails from pop3 into a text file with this python code:

def Download(pop3,username,password):
try:
    Mailbox = poplib.POP3(pop3, '110') 
    Mailbox.user(username) 
    Mailbox.pass_(password) 
    numMessages = len(Mailbox.list()[1])
    for i in range(numMessages):
        logfile = open(username + '.log', 'a')                    
        logfile.write('\n')                    
        for msg in Mailbox.retr(i+1)[1]:
            print msg                   
            logfile.write('%s\n' % (msg))                    
        logfile.close()
    Mailbox.quit()
except KeyboardInterrupt:
    print 'Exit'
    sys.exit(1)

My problem is the email is encrypted in base64, how I can call only email body for decryption?

base64.b64decode(body)

Solution

  • You should use the email-package to parse emails. The get_payload-method on the parsed message object can handle the decoding for you when using the decode=True argument.

    For a simple (non-multipart) message, it would look something like this:

    import email.parser
    ...
    parser = email.parser.FeedParser()
    for msg in Mailbox.retr(i+1)[1]:
        parser.feed(msg + '\n')
    message = parser.close()
    payload = message.get_payload(decode=True)
    print(payload)
    ...