Code Example of Email Receiving by IMAP
Python3:
# -*- coding:utf-8 -*-
import imaplib
import email
from imapclient import imap_utf7
def get_folders():
# Obtain the list of email folders.
list_folder = []
list_folder_org = conn.list()
for i in list_folder_org[1]:
list_folder.append(imap_utf7.decode(i).split('/" ')[1].replace('"', '')) # Capture the folder name.
print(list_folder)
return list_folder
def get_content(msg):
# Decode the email content
if msg.is_multipart():
# List
return get_content(msg.get_payload(0)) # Get the text in the email
else:
# String
return msg.get_payload(None,
decode=True) # Obtain the text in the email. If it is True, it will decode the encoded content in Base64/ Quota-printable format. Otherwise, it will not be decoded.
host = 'imap.sg.aliyun.com'
user = 'xxxxxx'
pwd = 'xxxxxx'
# Connect to the server and login
# conn = imaplib.IMAP4(host, 143)
conn=imaplib.IMAP4_SSL (host, 993) # SSL-encrypted connection
# Authenticated logon.
conn.login(user, pwd)
print ('Email folder list:')
get_folders() # Obtain the list of email folders.
folder_name=imap_utf7.encode ('INBOX') # utf-7 code, Chinese code
conn.select(folder_name) # 'draft','INBOX' # Select the folder.
v_type, data=conn.search (None, UNSEEN SINCE 05-Mar-2022) # Query unread emails after a specified date.
email_list = data[0].split()
if len(email_list) == 0:
print ('Folder is empty, exit! ')
exit(1)
print ('Status=', v_type, 'MSMQ sequence num=', data)
print ('All UIDs in this folder:', conn.uid('search', None, "ALL"))
# Obtain the sequence number of the last email.
item = email_list[len(email_list) - 1]
print ('The MSMQ sequence number of the last email num:', item)
v_status = conn.status(folder_name, '()')
v_status_1 = v_status[1][0].decode ('utf-8').replace('MESSAGES', 'Total emails in the mailbox:').replace('RECENT',
'Number of emails marked as \RECENT in the mailbox:').replace(
'UIDNEXT', 'Next UID that can be assigned to a new email:').replace('UIDVALIDITY', 'UID validity flag of the mailbox:').replace('UNSEEN', 'Unread emails:')
print ('Basic folder information of mailbox:', folder_name, v_status_1)
v_count = 1
list_show_yulan = []
# Resolve the email.
for num in email_list:
v_type, data = conn.fetch(num, '(RFC822)')
UID = conn.fetch(num, 'UID')[1]
v_num_uid = UID[0].decode('utf-8').replace('(', '').replace(')', '').split(' ')
print('\nResolve' + str(v_count) + 'email, num=', v_num_uid[0], 'UID=', v_num_uid[2],
'===============================================')
print ('Server return value=', data[0]) # The returned result, which contains the num,UID, and original message.
msg = email.message_from_bytes(data[0][1])
print ('original email:\n', msg)
v_count = v_count + 1
conn.print_log() # Print IMAP logs
conn.close()