如何使用 python imaplib.IMAP4.search() 搜索特定的电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19001266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to search specific e-mail using python imaplib.IMAP4.search()
提问by yayun
import imaplib,time
T=time.time()
M=imaplib.IMAP4_SSL("imap.gmail.com")
M.login(user,psw)
M.select()
typ, data = M.search(None, 'UNSEEN SINCE T')
for num in string.split(data[0]):
try :
typ, data=M.fetch(num,'(RFC822)')
msg=email.message_from_string(data[0][1])
print msg["From"]
print msg["Subject"]
print msg["Date"]
except Exception,e:
print "hello world"
M.close()
M.logout()
ERROR:
错误:
Traceback (most recent call last):
File "mail.py", line 37, in <module>
typ, data = M.search(None, 'UNSEEN SINCE T')
File "/usr/lib/python2.7/imaplib.py", line 627, in search
typ, dat = self._simple_command(name, *criteria)
File "/usr/lib/python2.7/imaplib.py", line 1070, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/lib/python2.7/imaplib.py", line 905, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: SEARCH command error: BAD ['Parse command error']
I want to search e-mail since a specific time . Here is my code .But it runs error.Can you give me some advice on how to solve it.thanks a lot!
我想从特定时间搜索电子邮件。这是我的代码。但它运行错误。你能给我一些关于如何解决它的建议。非常感谢!
回答by Owen
UPDATE: OP has imported imaplib but it's still generating an error message which has not been put into the question.
更新:OP 已导入 imaplib,但它仍然生成一条错误消息,该消息尚未纳入问题。
--
——
This won't work because you have not imported imaplib.
这将不起作用,因为您尚未导入 imaplib。
Try
尝试
import smtplib, time, imaplib
instead of
代替
import smtplib, time
回答by user1974278
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('[email protected]', 'test')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
result, data = mail.search(None, '(FROM "anjali sinha" SUBJECT "test")' )
ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest
result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID
raw_email = data[0][1] # here's the body, which is raw text of the whole email
# including headers and alternate payloads
print raw_email
打印 raw_email
this eventually worked for me specyfing labels with conditions
这最终对我有用,指定有条件的标签