0

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)
tripleee
  • 175,061
  • 34
  • 275
  • 318
AutoSoft
  • 191
  • 1
  • 1
  • 11

2 Answers2

3

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)
...
mata
  • 67,110
  • 10
  • 163
  • 162
  • numMessages = len(Mailbox.list()[1]) for i in range(numMessages): 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) Mailbox.quit() im edit my script bat not working ... File "c:\GetMails.py", line 17, in Download parser = email.parser.FeedParser() NameError: global name 'email' is not defined – AutoSoft Dec 16 '12 at 16:11
  • what is name of package import ? im try : Import parser and not working teh script. – AutoSoft Dec 16 '12 at 17:47
  • `import email.parser`. I've already updated my answer to include that line before... – mata Dec 16 '12 at 19:16
1

Try the following on your text:

import base64

base64.decodestring(string_to_decode)

As an example:

In [1]: import base64

In [2]: base64.encodestring("alpha beta gamma")
Out[2]: 'YWxwaGEgYmV0YSBnYW1tYQ==\n'

In [3]: test = base64.encodestring("alpha beta gamma")

In [4]: base64.decodestring(test)
Out[4]: 'alpha beta gamma'

In your case, you should have:

msg = base64.decodestring(msg)
logfile.write('%s\n' % (msg))

Just pay attention to what is msg; if it is not a base64 string, you should split the result so that you get the base64 encoded part you want.

Rubens
  • 14,478
  • 11
  • 63
  • 92