Imaplib.error: FETCH command is illegal in AUTH state

I am trying to download attachments from Gmail using a combination of code snippets that I found on the Internet and some editing from me. However, the following code:

import email, getpass, imaplib, os, random, time
import oauth2 as oauth
import oauth2.clients.imap as imaplib

MY_EMAIL = 'example@gmail.com'
MY_TOKEN = "token"
MY_SECRET = "secret"

consumer = oauth.Consumer('anonymous', 'anonymous')
token = oauth.Token(MY_TOKEN, MY_SECRET)

url = "https://mail.google.com/mail/b/"+MY_EMAIL+"/imap/"
m = imaplib.IMAP4_SSL('imap.gmail.com')

m.authenticate(url, consumer, token)

m.select('INBOX')

items = m.select("UNSEEN"); 
items = items[0].split() 

for emailid in items:
    data = m.fetch(emailid, "(RFC822)")

returns this error:

imaplib.error: FETCH command illegal in AUTH state

Why was Fetch illegal while I am logged in?

+3
source share
2 answers

You do not have enough error checking on your calls to choose. As a rule, this is how I will structure the first parts of the connection to the mailbox:

# self.conn is an instance of IMAP4 connected to my server.
status, msgs = self.conn.select('INBOX')

if status != 'OK':
  return # could be break, or continue, depending on surrounding code.

msgs = int(msgs[0])

, , , , , , , , "", , , , . , . ( , "UNSEEN" ). , :

('NO', ['The requested item could not be found.'])

for email id in items . , , . , , :

('OK', ['337'])

, .

, , :

status, msgs = self.conn.select('INBOX')
# returns ('OK', ['336'])

status, ids = self.conn.search(None, 'UNSEEN')
# returns ('OK', ['324 325 326 336'])

if status == 'OK':
  ids = map(int, ids[0].split())

select, .

+3

Source: https://habr.com/ru/post/1796404/


All Articles