python的imaplib实现搜索邮件

废话不说了,也踩了几个坑,直接上代码,后边再研究email模块如何解析邮件

#!/usr/bin/python

import imaplib


# 统计邮件数量的方法
def get_mail_count(mail_data):
    ids = mail_data[0]
    ret = ids.decode('utf-8')
    message_id_list = ret.split()
    return len(message_id_list)


# 读出邮件细节的方法
def get_mail_detail(mail_data):
    msg = mail_data[0]
    msg_list = msg.split()
    print(msg_list)
    for ids in msg_list:
        results, data = imap_object.fetch(ids, "(RFC822)")
        print(data)


imap_user = 'xxoo@fuck.com'
imap_object = imaplib.IMAP4('250.250.250.250', 143)
imap_object.login(imap_user, 'fuck')

imap_object.select('INBOX')  # connect to inbox.
# typ, msg_ids = imap_object.search(None, 'SUBJECT "测试"'.encode('utf-8')) # 根据主题模糊查询
typ, msg_ids = imap_object.search(None, '(FROM "ooxx@fuck.com")')  # 根据往来联系人
count1 = get_mail_count(msg_ids)
print(count1)
get_mail_detail(msg_ids)

imap_object.select('"Sent Items"')  # connect to Sent Items
# typ2, msg_ids2 = imap_object.search(None, 'SUBJECT "测试"'.encode('utf-8')) # 根据主题模糊查询
typ2, msg_ids2 = imap_object.search(None, '(TO "ooxx@fuck.com")')  # 根据往来联系人
count2 = get_mail_count(msg_ids2)
print(count2)
get_mail_detail(msg_ids2)

""" or 或的关系 不加就是 and 中文主题要encode utf-8 有的邮箱可能编码也不好使 status, message = imap_object.search(None, 'OR FROM "ooxx@fuck.com"', 'SUBJECT "测试"'.encode('utf-8')) """

imap_object.close()


    原文作者:低调说
    原文地址: https://blog.csdn.net/hans99812345/article/details/120825679
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞