pythonpython-3.xemailbase64imaplib

How to read email content in Python 3


I've tried many code to access and read email content, for example, about Gmail i only can do authentication and with Outlook i have code that can read email but it's encrypted...but now it only access email and doesn't output with encrypted information. So i need help to solve this. Thanks

Here's the code:

import imaplib
import base64 

email_user = input('Email: ')
email_pass = input('Password: ')

M = imaplib.IMAP4_SSL('imap-mail.outlook.com', 993)
M.login(email_user, email_pass)
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    num1 = base64.b64decode(num1)
    data1 = base64.b64decode(data)
    print('Message %s\n%s\n' % (num, data[0][1]))
M.close()
M.logout()

Solution

  • I've checked through your code anyway, and there are a couple of comments. The first one is that commas seem to have been stripped out when you pasted the code in here. I've tried to put them back, so check that my code does match yours. Remember that without access to Outlook, I can't test my suggestions.

    import imaplib
    import base64
    email_user = input('Email: ')
    email_pass = input('Password: ')
    
    M = imaplib.IMAP4_SSL('imap-mail.outlook.com', 993)
    M.login(email_user, email_pass)
    M.select()
    
    typ, data = M.search(None, 'ALL')
    
    for num in data[0].split():
        typ, data = M.fetch(num, '(RFC822)')   # data is being redefined here, that's probably not right
        num1 = base64.b64decode(num1)          # should this be (num) rather than (num1) ?
        data1 = base64.b64decode(data)
        print('Message %s\n%s\n' % (num, data[0][1]))  # don't you want to print num1 and data1 here?
    
    M.close()
    M.logout()
    

    Assuming that's correctly reconstituted, you call your message list data on line 10, but then re-assign the results of calling fetch() to data on line 13.

    On line 14, you decode num1, which hasn't been defined yet. I'm not sure that the numbers need decoding though, that seems a bit strange.

    On line 16, you're printing the encoded values, not the ones you've decoded. I think you may want something like

    import imaplib
    import base64
    email_user = input('Email: ')
    email_pass = input('Password: ')
    
    M = imaplib.IMAP4_SSL('imap-mail.outlook.com', 993)
    M.login(email_user, email_pass)
    M.select()
    
    typ, message_numbers = M.search(None, 'ALL')  # change variable name, and use new name in for loop
    
    for num in message_numbers[0].split():
        typ, data = M.fetch(num, '(RFC822)')
        # num1 = base64.b64decode(num)          # unnecessary, I think
        print(data)   # check what you've actually got. That will help with the next line
        data1 = base64.b64decode(data[0][1])
        print('Message %s\n%s\n' % (num, data1))
    
    M.close()
    M.logout()
    

    Hope that helps.