Alibaba Mail IMAP example: Search for emails by subject keyword
Updated at:
The SEARCH command does not currently support searching for subjects using the '(UNSEEN SUBJECT "test")' format. First, you can narrow the search scope by date or read/unread status. Then, you can use FETCH to retrieve the content and find a match.
Python example code
Scenario: Search for unread emails in the inbox, fetch their subjects, and identify the subjects that contain "tes". Then, print the email ID and the original .eml content for each matching email.
Important
Note: This code was tested in Python 3.11.9. Test the code thoroughly before you use it in a production environment.
# -*- coding: utf-8 -*-
import imaplib
from imapclient import imap_utf7
# Configure the IMAP server
imap_server = 'imap.qiye.aliyun.com' # IMAP server address
username = 'test@example.com' # Username
password = '********' # Password
port = 993 # Port number
# Connect to the IMAP server
mail = imaplib.IMAP4_SSL(imap_server, port)
mail.login(username, password)
# Select a mailbox (for example, "INBOX")
folder_name = imap_utf7.encode('INBOX') # Encode the folder name to UTF-7. This is required for folder names that contain Chinese characters.
mail.select(folder_name)
# Search for unread emails
status, data = mail.search(None, 'UNSEEN')
if status == 'OK':
mail_ids = data[0].split()
for mail_id in mail_ids:
# Fetch the email subject
f_status, msg_data = mail.fetch(mail_id, '(BODY[HEADER.FIELDS (SUBJECT)])')
if f_status == 'OK':
subject = msg_data[0][1].decode().splitlines()[0]
if 'Subject:' in subject and 'tes' in subject:
# Fetch the full email content
f_status, msg_data = mail.fetch(mail_id, '(RFC822)')
if f_status == 'OK':
print(f"Email ID: {mail_id.decode()}")
print("Email body:")
print(msg_data[0][1].decode())
# Close the connection
mail.logout()
Result

Is this page helpful?