Alibaba Mail IMAP command: IDLE (idle state)

更新时间:
复制 MD 格式

The IDLE command allows a client to receive new mail notifications without frequently polling the server.

The IDLE command allows a client to enter an idle state. In this state, the server pushes notifications to the client when new mail arrives.

The IDLE command has the following features and benefits:

  • Real-time notifications: The IDLE command enables an IMAP client to receive real-time notifications for new mail. This eliminates the need for periodic mailbox checks and reduces latency.

  • Resource conservation: Compared to frequent polling, IDLE conserves server and network resources because data is transferred only when new mail arrives.

  • Improved user experience: Users are notified of new mail in real time and do not need to manually refresh their mail list.

When a client sends an IDLE request, it enters a waiting state. The server then sends a notification when a specific event occurs, such as the arrival of new mail. The client must handle these notifications. After processing a notification, the client can choose to remain in the IDLE state or exit it.

Python example code

Important

Security warning: The following code was tested on Python 3.11.9. You must test the code thoroughly before you use it in a production environment.

# -*- coding: utf-8 -*-
import imaplib
import time

from imapclient import imap_utf7


# Enter IDLE mode
def idle():
    """
    Puts the mail client into IDLE mode to listen for mailbox changes in real time.
    This function sends the IDLE command to the IMAP server and continuously listens for server responses.
    It prints corresponding information when new mail arrives, mail is deleted, or mail status changes.
    """
    # Send the IDLE command
    mail.literal = b'IDLE'
    mail.send(b'a001 IDLE\r\n')
    # Set the timeout
    # start_time = time.time()  # Record the start time
    # timeout = 3600  # Timeout is 1 hour
    # Wait for the server response and keep the connection alive
    # while time.time() - start_time < timeout:
    while True:
        print("===========================================")
        print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        # This read operation blocks and waits. A response appears after about 30 seconds of mailbox activity.
        response = mail.readline()  # Read the server response
        if response:
            print(f"Received: {response.decode()}")
        if b'EXISTS' in response:
            print("Mailbox changed (new mail, deleted mail, etc.)!")
            # Add code here to process new mail, such as retrieving new mail information.
        elif b'FETCH (FLAGS (\Seen))' in response:
            print("A message was marked as read")
        elif b'FETCH (FLAGS ())' in response:
            print("A message was marked as unread")
        elif b'EXPUNGE' in response:
            print("A message was deleted")
        elif b'+ idling' in response:
            print("Continuing to wait")
        else:
            print("Other response:", response)


# Set mailbox information
imap_server = 'imap.qiye.aliyun.com'
username = 'test@example.com'
password = '*********'
imap_port = 993

# Connect to the IMAP server
mail = imaplib.IMAP4_SSL(imap_server)
# Log on
mail.login(username, password)

# Select a mailbox
folder_name = imap_utf7.encode('inbox')
mail.select(folder_name)  # UTF-7 encoding for Chinese characters
print("Entering IDLE mode...")
idle()  # Wait for server responses
Note
  • When you perform an operation in the Alibaba Mail web client, such as receiving new mail or marking mail as read, a response is received in approximately 30 seconds.

  • The IDLE state is maintained for approximately 5 minutes, after which the server terminates the connection.

Example output

image