使用Python删除Gmail中的特定电子邮件

问题描述

运行脚本时,我一直收到此错误,该脚本仅用于删除来自特定发件人的电子邮件:

Traceback (most recent call last):
  File "/Users/philip/Desktop/Python Projects/email_organizer/eorger.py",line 33,in <module>
    deleteEmail(email,pwd,imapserver)
  File "/Users/philip/Desktop/Python Projects/email_organizer/eorger.py",line 24,in deleteEmail
    typ,data=mail.search(None,'Robinhood@prospectusdocs.com')
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/imaplib.py",line 734,in search
    typ,dat = self._simple_command(name,*criteria)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/imaplib.py",line 1230,in _simple_command
    return self._command_complete(name,self._command(name,*args))
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/imaplib.py",line 1055,in _command_complete
    raise self.error('%s command error: %s %s' % (name,typ,data))
imaplib.error: SEARCH command error: BAD [b'Could not parse command']

这是我的代码会产生此错误:

import imaplib

# your email address
email='test@gmail.com'
# your email password
pwd='************'

# need to input imap server to connect to gmail
imapserver='imap.gmail.com'

def deleteEmail(email,IMAP):
    mail=imaplib.IMAP4_SSL(IMAP) # connect to server
    mail.login(email,pwd) # user server to login to gmail account

    mail.select('inbox') # selects the 'inbox' to look into
    # search for specific criteria in selected inbox
    typ,'Robinhood@prospectusdocs.com')

    for num in data[0].split():
        mail.store(num,'+FLAGS',r'(\Deleted)')

    mail.expunge()
    mail.close()
    mail.logout()

deleteEmail(email,imapserver)

有什么建议吗?

解决方法

它适用于

python v3.4.1

或者您可以访问Unable to retrieve gmail messages from any folder other than inbox (Python3 issue)

import imaplib
import email

m = imaplib.IMAP4_SSL("imap.gmail.com",993)
m.login("myemail@gmail.com","mypassword")
m.select('"[Gmail]/All Mail"')

result,data = m.uid('search',None,"ALL") # search all email and return uids
if result == 'OK':
    for num in data[0].split():
    result,data = m.uid('fetch',num,'(RFC822)')
    if result == 'OK':
        email_message = email.message_from_bytes(data[0][1])    # raw email text including headers
        print('From:' + email_message['From'])

m.close()
m.logout()
,
User

https://github.com/ikvk/imap_tools

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...