Search code examples
pythonpython-3.xgmailimaplib

Python imaplib fetch returns "Couldn't parse command" error


I have been looking for this error for hours and couldn't find anything that solves my problem. I was following an article on this topic while doing this. I wasn't even getting this error before. What I understand from the fetch part is It is separating messages from my box. Tried different methods but nothing seems to work for me. Edit: I decided that my question was a little bit wrong. I actually need to know what I am doing wrong or what part should I change.

dic_path = "Mails\\"
username = "username@gmail.com"
password = "password"

imap = imaplib.IMAP4_SSL("imap.gmail.com")

imap.login(username, password)

status, messages = imap.select()

N = 10

messages = int(messages[0])
for i in range(messages, messages-N, -1):
    res, msg = imap.fetch(str(i), "(RFC822)")
for response in msg:
    if isinstance(response, tuple):
        # parse a bytes email into a message object
        msg = email.message_from_bytes(response[1])
        # decode the email subject
        subject = decode_header(msg["Subject"])[0][0]

Error;

Traceback (most recent call last):
  File "C:\Users\Teknoloji\Desktop\Projects\Python Projects\Phyton\DiscordBot\DiscordBot2\Main.py", line 28, in <module>
    res, msg = imap.fetch(str(i), "(RFC822)")
  File "C:\Users\Teknoloji\AppData\Local\Programs\Python\Python38-32\lib\imaplib.py", line 539, in fetch
    typ, dat = self._simple_command(name, message_set, message_parts)
  File "C:\Users\Teknoloji\AppData\Local\Programs\Python\Python38-32\lib\imaplib.py", line 1205, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "C:\Users\Teknoloji\AppData\Local\Programs\Python\Python38-32\lib\imaplib.py", line 1030, in _command_complete
    raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: FETCH command error: BAD [b'Could not parse command']

Debug trace: https://pastebin.com/raw/1fAPzGsv


Solution

  • Your pastebin indicates that your mailbox has 8 messages in it, but you are trying to fetch the most recent 10.

     46:51.53 < b'* 8 EXISTS'
    

    You eventually count backwards to zero, which is an invalid message number:

    46:52.45 > b'MAAK11 FETCH 0 (RFC822)'
    46:52.53 < b'MAAK11 BAD Could not parse command'
    

    The server then throws an error.

    So, make sure you never count below the first message:

    for i in range(messages, max(messages-N, 1), -1):