首先得到邮件id:
_type, _search_data = email_server.search(None, 'ALL')
email_id_list = _search_data[0].split() # 转成标准列表,获得所有邮件的ID
然后解析每一个邮件:
_result, _email_data = email_server.fetch(_mail_id, '(RFC822)') # 通过邮件id获取邮件
email_info = email.message_from_bytes(_email_data[0][1]) # 邮件内容
subject = email.header.make_header(email.header.decode_header(email_info['SUBJECT'])) # 主题
mail_from = email.header.make_header(email.header.decode_header(email_info['From'])) # 发件人
import imaplib
import email
from loguru import logger
def main():
imap_config = {
'imap_server': 'imap.exmail.qq.com',
'username': '[email protected]',
'password': 'xxxxx',
}
# 连接到邮箱服务器
email_server = imaplib.IMAP4_SSL(imap_config['imap_server'])
email_server.login(imap_config['username'], imap_config['password'])
email_server.select('INBOX')
# 选择收件箱
_type, _search_data = email_server.search(None, 'ALL')
# 开始解析
email_id_list = _search_data[0].split() # 转成标准列表,获得所有邮件的ID
logger.info(f'一共解析邮件数量:{len(email_id_list)}')
# 解析内容:
for _mail_id in email_id_list:
_result, _email_data = email_server.fetch(_mail_id, '(RFC822)') # 通过邮件id获取邮件
email_info = email.message_from_bytes(_email_data[0][1]) # 邮件内容(未解析)
subject = email.header.make_header(email.header.decode_header(email_info['SUBJECT'])) # 主题
mail_from = email.header.make_header(email.header.decode_header(email_info['From'])) # 发件人
logger.info("----------- === ----------- === ----------- === -----------")
logger.info("邮件的subject是%s" % subject)
logger.info("邮件的发件人是%s" % mail_from)
email_server.close()
email_server.logout()
if __name__ == '__main__':
main()