簡體   English   中英

如何使用python imaplib.IMAP4.search()搜索特定的電子郵件

[英]How to search specific e-mail using python imaplib.IMAP4.search()

 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()

錯誤:

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']

我想在特定時間搜索電子郵件。 這是我的代碼。但它運行錯誤。你可以給我一些如何解決它的建議。謝謝你們!

import imaplib

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('test@gmail.com', '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

這最終對我來說有條件的specyfing標簽

更新:OP已導入imaplib,但它仍然生成一條錯誤消息,但尚未提出問題。

-

這不起作用,因為您沒有導入imaplib。

嘗試

import smtplib, time, imaplib

代替

import smtplib, time

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM