0

I want to get G-mail with Google account by using IMAP. So I found some basic code how to use IMAP. And I run it with my Google account. But I get some errors. I don't know role of functions or parameters so please help me if you have gmail account and know the role of functions.

This is my code and I conceal my account information so the real account is different to mine.

#!/usr/bin/env python

import sys
import imaplib
import getpass
import email
import email.header
import datetime
EMAIL_ACCOUNT = "id@gmail.com"
EMAIL_PASSWORD = "password"
# Use 'INBOX' to read inbox.  Note that whatever folder is specified,
# after successfully running this script all emails in that folder
# will be marked as read.
EMAIL_FOLDER = "Top Secret/PRISM Documents"
def process_mailbox(M):

rv, data = M.search(None, "ALL")
if rv != 'OK':
    print("No messages found!")
    return
    for num in data[0].split():
        rv, data = M.fetch(num, '(RFC822)')
        if rv != 'OK':
            print("ERROR getting message", num)
            return
        msg = email.message_from_bytes(data[0][1])
        hdr = 
        email.header.make_header(email.header.decode_header(msg['Subject']))
        subject = str(hdr)
        print('Message %s: %s' % (num, subject))
        print('Raw Date:', msg['Date'])
        # Now convert to local date-time
        date_tuple = email.utils.parsedate_tz(msg['Date'])
        if date_tuple:
            local_date = datetime.datetime.fromtimestamp(
                email.utils.mktime_tz(date_tuple))
            print ("Local Date:", \
                local_date.strftime("%a, %d %b %Y %H:%M:%S"))
M = imaplib.IMAP4_SSL('imap.gmail.com')
try:
    rv, data = M.login(EMAIL_ACCOUNT, EMAIL_PASSWORD)
except imaplib.IMAP4.error:
    print ("LOGIN FAILED!!! ")
    sys.exit(1)
print(rv, data)
rv, mailboxes = M.list()
if rv == 'OK':
    print("Mailboxes:")
    print(mailboxes)
rv, data = M.select(EMAIL_FOLDER)
if rv == 'OK':
    print("Processing mailbox...\n")
    process_mailbox(M)
    M.close()
else:
    print("ERROR: Unable to open mailbox ", rv)
M.logout()

This is the error result. enter image description here

This is errors in text.

C:\Users\user\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/user/PycharmProjects/Server/imap.py
OK [b'testpopteam2@gmail.com authenticated (Success)']
Mailboxes:
[b'(\\HasNoChildren) "/" "INBOX"', b'(\\HasChildren \\Noselect) "/" "[Gmail]"', b'(\\Flagged \\HasNoChildren) "/" "[Gmail]/&vMTUXNO4ycDVaA-"', b'(\\HasNoChildren \\Sent) "/" "[Gmail]/&vPSwuNO4ycDVaA-"', b'(\\HasNoChildren \\Junk) "/" "[Gmail]/&wqTTONVo-"', b'(\\Drafts \\HasNoChildren) "/" "[Gmail]/&x4TC3Lz0rQDVaA-"', b'(\\All \\HasNoChildren) "/" "[Gmail]/&yATMtLz0rQDVaA-"', b'(\\HasNoChildren \\Important) "/" "[Gmail]/&yRHGlA-"', b'(\\HasNoChildren \\Trash) "/" "[Gmail]/&1zTJwNG1-"']
Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/Server/imap.py", line 73, in <module>
    rv, data = M.select(EMAIL_FOLDER)
  File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 737, in select
    typ, dat = self._simple_command(name, mailbox)
  File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 1188, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 1019, in _command_complete
    raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: SELECT command error: BAD [b'Could not parse command']

Process finished with exit code 1
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Jung
  • 81
  • 10
  • I paste the errors as text but those are difficult to figure out because of path. – Jung Apr 08 '17 at 13:44
  • If you change your `EMAIL_FOLDER` to match one of the values in the `mailboxes` list, does that change things? – Charles Duffy Apr 08 '17 at 13:45
  • ...btw, it looks like your syntax highlighting is wrong -- there's no indent after `def process_mailbox(M):`. In the future, consider selecting your *whole* code and using the `{}` button to indent a region to be considered code. – Charles Duffy Apr 08 '17 at 13:46
  • 1
    Oh! Thanks! I changed EMAIL_FOLDER value and I finally get mail! – Jung Apr 08 '17 at 13:54
  • And I will use { } button next question. Thank you for your advice. – Jung Apr 08 '17 at 13:56

1 Answers1

0

The call to

M.select(EMAIL_FOLDER)

isn't including any of the mailboxes returned from:

rv, mailboxes = M.list()

Ensure that the mailbox name is valid.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 1
    Also, I believe imaplib has a bug where it doesn't quote folder names if they have spaces in them, so that may need to be done manually. – Max Apr 08 '17 at 15:06