用于在Gmail上删除邮件的Python脚本[replicate]

nom7f22z  于 2023-03-07  发布在  Python
关注(0)|答案(1)|浏览(227)

This question already has answers here:

Permanently delete Gmail email using Python imaplib (2 answers)
Closed 11 hours ago.
I want to create a script to access a gmail accouunt , go to a particular category i.e 'Promotions' and delete mails from a sender.
So far I made this :

import imaplib

# login to your Gmail account
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('mail@gmail.com', 'password')

# select the Promotions category
mail.select('Promotions')

# search for emails from a particular sender
result, data = mail.search(None, 'FROM "sender@gmail.com')

# delete the emails
for num in data[0].split():
    mail.store(num, '+FLAGS', '\\Deleted')
mail.expunge()

# logout from your Gmail account
mail.close()
mail.logout()

I kept getting this errors on pycharm

`Traceback (most recent call last):

File "C:\Users\Documents\Python Tutorials\Projects\mail_script.py", line 11, in result, data = mail.search(None, 'FROM "sender@gmail.com"') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\imaplib.py", line 734, in search typ, dat = self._simple_command(name, *criteria) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\imaplib.py", line 1230, in _simple_command return self._command_complete(name, self._command(name, *args)) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\imaplib.py", line 968, in _command raise self.error("command %s illegal in state %s, " imaplib.IMAP4.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED`

yqlxgs2m

yqlxgs2m1#

import imaplib

# login to your Gmail account
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('mail@gmail.com', 'password')

# select the Promotions category
mail.select('Promotions')

# select all messages from the sender
mail.select('INBOX')
result, data = mail.uid('search', None, 'FROM "sender@gmail.com"')

# delete the emails
if data[0]:
    for uid in data[0].split():
        mail.uid('store', uid, '+FLAGS', '\\Deleted')
    mail.expunge()

# logout from your Gmail account
mail.close()
mail. Logout()

相关问题