2014-05-01 44 views
1

我一直在學習如何使用python imaplib庫來處理我正在處理的項目,但是我看到一些讓我難以接受的行爲。當我嘗試使用「NOT FROM」進行搜索時,它會返回與「FROM」相同的結果,就好像它不在那裏一樣。我的假設是,我只是把錯誤的命令,但我已經搜索了幾個例子,我發現每一個例子似乎這樣做我的方式。python imaplib搜索'NOT'關鍵字

import imaplib 
mail = imaplib.IMAP4_SSL(host) 
mail.login(email, pw) 
mail.select(mailbox) 
# The following two work as expeceted 
# and give different results 
mail.uid('search', None, '(NOT NEW)') 
mail.uid('search', None, '(NEW)') 
# However the following two give the same 
mail.uid('search', None, '(FROM gmail)') 
mail.uid('search', None, '(NOT FROM gmail)') 

我已經嘗試過所有可以輸入的方法,但我可以想到,但它們都不起作用。我已經檢查了兩個RFC2060,一個是imaplib所說的,它是基於和一些更新的。

$ python --version 
Python 2.7.5+ 

有沒有人看到我在搞亂或者也看到了這個問題?很少有出有這個特定庫似乎


編輯: 我看着這個遠一點,它似乎專門是一個問題,我連接到IMAP服務器..嘗試過的OpenSSL與

$ openssl s_client -connect imap.mail.yahoo.com:993 -crlf 

連接和登錄,並試圖

UID SEARCH FROM "gmail" 
UID SEARCH NOT FROM "gmail" 

後,我得到了相同的行爲。

然而,當我連接到Gmail帳戶

$ openssl s_client -connect imap.gmail.com:993 -crlf 

,並嘗試

UID SEARCH FROM "gmail" 
UID SEARCH NOT FROM "gmail" 

我得到預期的行爲。

我想這是「解決」,然後

+0

我檢查了你的代碼,工作正常。 – Mortezaipo

+0

謝謝!但我不確定你的意思,我知道它運行得很好。問題是,從「foo」返回相同的FROM「foo」。你的意思是說這不會發生在你身上嗎? (您是否嘗試過使用雅虎郵件?因爲它似乎是問題的根源。) – user3591723

+0

我嘗試過使用Gmail,但使用的不是'gmail',它讓我感到:('OK',['21 23 24 25 35 )('OK',['12 13 14 15 16 17 18 19 20 22 26 27 28 29 30 31 32 33 34 36']) – Mortezaipo

回答

0

我看着這個遠一點,它似乎專門是一個問題,我連接到IMAP服務器。 。我在嘗試後超過openssl的

$ openssl s_client -connect imap.mail.yahoo.com:993 -crlf 

連接和登錄,並試圖

UID SEARCH FROM "gmail" 
UID SEARCH NOT FROM "gmail" 

我得到相同的行爲。

然而,當我連接到Gmail帳戶

$ openssl s_client -connect imap.gmail.com:993 -crlf 

,並嘗試

UID SEARCH FROM "gmail" 
UID SEARCH NOT FROM "gmail" 

我得到預期的行爲。

我想這是「解決」然後

0

NOT FROM gmail工作正常在Gmail的IMAP,但是關於雅虎這是行不通的。

試試:

import imaplib 
## connect to imap server 
mail = imaplib.IMAP4_SSL('imap.mail.yahoo.com') 
mail.login('username','password') 
mail.select('inbox') 

## search all mails 
all_mail = mail.search(None,'ALL') 

## search all gmails 
all_gmail = mail.search(None,'(FROM "gmail")') 

## make them as list of int 
all_mail = [x for x in all_mail[1][0].split() if x != ""] 
all_gmail = [x for x in all_gmail[1][0].split() if x != ""] 
not_gmail = [x for x in all_mail if x not in all_gmail] 
#not_gmail = set(all_mail) - set(all_gmail)  

## get the output 
print "all mail: " + str(all_mail) 
print "all gmail: " + str(all_gmail) 
print "all not gmail: " + str(not_gmail) 

這是一個有點慢,但工作得很好。 而對於RFC看看到:

http://tools.ietf.org/html/rfc3501.html

http://tools.ietf.org/html/draft-ietf-imapext-regex-00

+1

我想出了一個類似的黑客,但我只是讓他們集,而不是因爲秩序對我來說並不重要:) 有點傻,雅虎沒有在我的意見工作條件搜索可用! – user3591723

+0

@ user3591723我只是找到這種方式。希望它對你有用。 ;) – Mortezaipo