Important
The following code was tested in Python 3.11.9. Test the code thoroughly before you use it in a production environment.
Python code examples
Scenario 1: Permanently delete all emails from a specified folder.
# -*- coding: utf-8 -*-
import imaplib
# Set mailbox information
# Configure the IMAP server
imap_server = 'imap.qiye.aliyun.com' # IMAP server address
username = 'test@example.com' # Username
password = '********' # Password
port = 993 # Port number
source_folder = 'folder2'
# Connect to the IMAP server
mail = imaplib.IMAP4_SSL(imap_server, port)
mail.login(username, password)
# Select the source folder
mail.select(source_folder)
# Search for the UIDs of all emails in the mailbox. This method is recommended.
result, uid_data = mail.uid('search', None, 'ALL')
print('Search result:', result, uid_data)
# If emails are found
if result == 'OK':
for uid in uid_data[0].split():
result, data = mail.uid('STORE', uid, '+FLAGS', '(\\Deleted)')
if result == 'OK':
print(f'{uid} deleted successfully')
# Log out
mail.close()
mail.logout()
Execution results

Scenario 2: Permanently delete an email with a specified UID.
# -*- coding: utf-8 -*-
import imaplib
def before_after_move_email(source_folder, destination_folder):
# Select a folder
mail.select(source_folder)
# UID
result, data = mail.uid('search', None, 'UNSEEN')
print(f'{source_folder} search result UID: {result}, {data}')
# Select a folder
mail.select(destination_folder)
# UID
result, data = mail.uid('search', None, 'UNSEEN')
print(f'{destination_folder} search result UID: {result}, {data}')
# Set mailbox information
# Configure the IMAP server
imap_server = 'imap.qiye.aliyun.com' # IMAP server address
username = 'test@example.com' # Username
password = '********' # Password
port = 993 # Port number
source_folder = 'folder1'
destination_folder = 'folder2'
# Connect to the IMAP server
mail = imaplib.IMAP4_SSL(imap_server, port)
mail.login(username, password)
print('Before deletion:')
before_after_move_email(source_folder, destination_folder)
mail.select(source_folder)
# Delete the specified UID
result, delete_data = mail.uid('STORE', '14', '+FLAGS', '(\\Deleted)')
mail.expunge()
print('After deletion:')
before_after_move_email(source_folder, destination_folder)
Execution results

该文章对您有帮助吗?