11

I am trying to search for messages in the Sent (actually i care for both) but I only get incoming messages. For the time being i have

imap_conn.select()
str_after = after.strftime('%d-%b-%Y')
typ, msg_ids = imap_conn.search('UTF-8','SINCE',str_after)

Which gives equivalent results with this

imap_conn.select('INBOX')

When I replace INBOX with ALL or SENT I get: command SEARCH illegal in state AUTH, only allowed in states SELECTED

PanosJee
  • 3,866
  • 6
  • 36
  • 49

5 Answers5

24

Man, the error message is so misleading. What it's really saying is that you have tried to select an invalid folder name hence the search operation fails.

To verify/check the current valid folders/labels do something like:

Using ImapClient

from imapclient import IMAPClient
## Connect, login and select the INBOX
imap_conn = IMAPClient('imap.gmail.com', use_uid=True, ssl=ssl)
imap_conn.login(USERNAME, PASSWORD)

print(imap_conn.list_folders())

Using imaplib

import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myusername@gmail.com', 'mypassword')
print(mail.list())

After I could see what folder names it was expecting, all was well.

RK1
  • 2,384
  • 1
  • 19
  • 36
w--
  • 6,427
  • 12
  • 54
  • 92
5

Make sure you use the extra quotes in your string:

imap_conn.select('"[Gmail]/Sent Mail"')  

That worked for me.

Max Quant
  • 386
  • 4
  • 7
4
import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com',993)
obj.login('userid','password')
obj.select('Sent')  # <-- response like ('OK', ['74']) --> total no. of mail in sent folder
obj.uid('SEARCH',None,'All') # <-- Returns the list of uids of the sent folder.
Avadhesh
  • 4,519
  • 5
  • 33
  • 44
  • 2
    It did not work on Gmail for me so I used: imap_conn.select('[Gmail]/Sent Mail') – PanosJee Sep 27 '10 at 22:12
  • 1
    'Sent' select Mails from 'Imap/Sent' folder & not from 'Gmail/Sent Mail' folder. If you Configure your gmail account in Thunderbird then it will automatically create 'Imap/Sent' Folder to place the copy of the sent mail in to that folder. if you want to select mails from 'Gmail/Sent Mail' folder then your code is ok. – Avadhesh Sep 28 '10 at 04:53
4

You need to use: imap_conn.select('[Gmail]/Sent Mail')

Just wanted to point this out for future users who see this. It's hidden in the comments.

Henley
  • 21,258
  • 32
  • 119
  • 207
  • 3
    Just a heads up: it seems the folder's name changes based on the language. For example for me `[Gmail]/Sent Mail` doesn't work but `[Gmail]/L&AOQ-hetetyt viestit` works (and vice versa if I change Gmail's display language from Finnish to English). – Felix Loether Jun 27 '12 at 09:44
1

Need to use print imap_conn.list(). Tags are language based. for example in spanish is [Gmail]/Todos

UmNyobe
  • 22,539
  • 9
  • 61
  • 90
Felix Martinez
  • 339
  • 2
  • 3