Python reads and parses mailbox emails, reads email subject, content, time

When python reads emails, you first need to enable the IMAP service or POP service in the mailbox, which can usually be enabled in the settings interface of the mailbox, but it seems that it is not enabled by default.

What is IMAP? What is the difference between IMAP and POP? : https://open.work.weixin.qq.com/help2/pc/19887?person_id=1

Taking Tencent mailbox as an example, in the same interface where the imap service is enabled, you will see the relevant configuration:

接收服务器:
imap.exmail.qq.com(使用SSL,端口号993)
发送服务器:
smtp.exmail.qq.com(使用SSL,端口号465)

Here we only read, so the corresponding configuration is:

import imaplib
email_value_config = {
    
    
	'imap_server': 'imap.exmail.qq.com', 
	'username': '[email protected]', 
	'password': 'xxxxx', 
}
email_server = imaplib.IMAP4_SSL(email_value_config['imap_server']) # 这样就已经链接到目标邮箱了
email_server.login(email_value_config["username"], email_value_config['password']) # 这里登录

Subsequent operations are:

  1. Select the content you want to operate, such as [Inbox], [Recycle Bin], etc., and use the program:

    email_server.select('INBOX')  # 选择【收件箱】
    

    Commonly used can refer to:

    INBOX 收件箱
    Sent Messages 已发送
    Drafts 草稿箱
    Deleted Messages 已删除
    Junk 垃圾箱
    
  2. Select the emails you want to extract according to the filter conditions, all the extractions can be used ALL, and then return the email id that meets the conditions, and lock the unique email according to the email id

sample program

import imaplib
import email
from email.utils import parsedate_to_datetime
from email.header import make_header, decode_header


email_value_config = {
    
    
	'imap_server': 'imap.exmail.qq.com', 
	'username': '[email protected]', 
	'password': 'xxxxx', 
}

def extract_email():
    email_server = imaplib.IMAP4_SSL(email_value_config['imap_server'])
    email_server.login(email_value_config["username"], email_value_config['password'])
    email_server.select('INBOX')  # 选择【收件箱】
    # 选择收件箱
    _typ, _search_data = email_server.search(None, 'ALL')
    # 开始解析
    mailidlist = _search_data[0].split()  # 转成标准列表,获得所有邮件的ID
    print(f'一共解析邮件数量:{
      
      len(mailidlist)}')
    # 解析内容:
    for mail_id in mailidlist:
        result, data = email_server.fetch(mail_id, '(RFC822)')  # 通过邮件id获取邮件
        email_message = email.message_from_bytes(data[0][1])  # 邮件内容(未解析)
        subject = make_header(decode_header(email_message['SUBJECT']))  # 主题
        mail_from = make_header(decode_header(email_message['From']))  # 发件人
        mail_dt = parsedate_to_datetime(email_message['Date']).strftime("%Y-%m-%d %H:%M:%S")  # 收件时间
        email_info = {
    
    
            "主题": str(subject),
            "发件人": str(mail_from),
            "收件时间": mail_dt,
        }
        print(email_info)


if __name__ == '__main__':
    extract_email()

ps: To view all optional mailboxes, you can use the following program:

# 查看全部可选择的邮箱:
for i in email_server.list()[1]:
    l = i.decode().split(' "/" ')
    print(l[0] + " = " + l[1])

Guess you like

Origin blog.csdn.net/weixin_35757704/article/details/132623569