Skip to content
Advertisement

imaplib “command SELECT illegal in state NONAUTH” error

I’m attempting to create an application to retrieve and analyse emails sent through gmail. I’m using an alteration on the tutorial found here; http://www.voidynullness.net/blog/2013/07/25/gmail-email-with-python-via-imap/

readmail.py

EMAIL_ACCOUNT = "*****"
PASSWD = "*****"
def process_mailbox(M):
    rv, data = M.search(None, "ALL")
    resp, items = 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']))
        if msg.is_multipart():
            for part in msg.get_payload():
                body = part.get_payload()
        subject = str(hdr)
        print('Message %s: %s' % (num, subject))
        print('Body:', body)

M = imaplib.IMAP4_SSL('imap.gmail.com',993)


try:
    rv, data = M.login(EMAIL_ACCOUNT, PASSWD)
except imaplib.IMAP4.error:
    print ("LOGIN FAILED!!! ")
    sys.exit(1)

print(rv, data)

rv, data = M.select("INBOX")
if rv == 'OK':
    print("Processing mailbox...n")
    process_mailbox(M)
    M.close()
else:
    print("ERROR: Unable to open mailbox ", rv)

M.logout()

When I run this code through the command line the output is as expected, however when ran through a basic flask import the entire thing falls apart.

app.py

from flask import Flask, render_template, jsonify, request
from readmail import process_mailbox
import json
import imaplib
app = Flask(__name__)

@app.route('/')
def homepage():
    return render_template('index.html')

@app.route('/test')
def test():
    return json.dumps({'name': process_mailbox(imaplib.IMAP4_SSL('imap.gmail.com',993)).subject})

if __name__ == '__main__':
    app.run(use_reloader=True, debug=True)

The error I receive is;

Traceback (most recent call last):
  File "C:Python34libsite-packagesflaskapp.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:Python34libsite-packagesflaskapp.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:Python34libsite-packagesflaskapp.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:Python34libsite-packagesflask_compat.py", line 33, in reraise
    raise value
  File "C:Python34libsite-packagesflaskapp.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:Python34libsite-packagesflaskapp.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:Python34libsite-packagesflaskapp.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:Python34libsite-packagesflask_compat.py", line 33, in reraise
    raise value
  File "C:Python34libsite-packagesflaskapp.py", line 1612, in 
full_dispatch_request
    rv = self.dispatch_request()
  File "C:Python34libsite-packagesflaskapp.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:UsersuserprojectflaskvenvProjectapp.py", line 13, in test
    return json.dumps({'name': 
process_mailbox(imaplib.IMAP4_SSL('imap.gmail.com',993)).subject})
  File "C:UsersuserprojectflaskvenvProjectreadmail.py", line 14, in process_mailbox
    M.select('"[Gmail]/All Mail"')
  File "C:Python34libimaplib.py", line 683, in select
    typ, dat = self._simple_command(name, mailbox)
  File "C:Python34libimaplib.py", line 1134, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "C:Python34libimaplib.py", line 882, in _command
    ', '.join(Commands[name])))imaplib.error: command SELECT illegal in state NONAUTH, only allowed in 
states AUTH, SELECTED

I’ve made several attempts this past week to find out ways to fix this error so any help would be appreciated.

Advertisement

Answer

Firstly, looking at the end of the traceback, you’ve got imaplib.error: command SELECT illegal in state NONAUTH, only allowed in states AUTH, SELECTED – and going back to the two lines in the traceback for your code:

app.py, test ... return json.dumps({'name': process_mailbox(imaplib.IMAP4_SSL('imap.gmail.com',993)).subject})
readmail.py process_mailbox ... M.select('"[Gmail]/All Mail"')

I’ve trimmed some excess here, but in test, you are only connecting to the Gmail IMAP server, but not logging in. The following code is what your ffirst file does:

M = imaplib.IMAP4_SSL('imap.gmail.com',993)

try:
    rv, data = M.login(EMAIL_ACCOUNT, PASSWD)
except imaplib.IMAP4.error:
    print ("LOGIN FAILED!!! ")
    sys.exit(1)

Also, process_mailbox will only return null, it changes the object you’ve passed directly.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement