邮件接收(IMAP)

接收邮件

# -*- coding:utf-8 -*-
from imapclient import IMAPClient
from log import Log
log = Log()
log = log.log()


class ImapMethod:
    def __init__(self, host, port, username, password):
        self.host = host            # 主机
        self.port = port            # 端口
        self.username = username    # 账号
        self.password = password    # 密码
        self.conn = None            # 连接

    def client(self, is_ssl=True):
        """连接服务器"""
        try:
            self.conn = IMAPClient(host=self.host, port=self.port, ssl=is_ssl)
            # self.conn.search()
            log.info("[邮箱] 连接服务器")
        except Exception as e:
            log.error("[邮箱] 连接服务器 失败 {}".format(e))
            raise e

    def login(self):
        """登录"""
        try:
            self.conn.login(self.username, self.password)
            self.conn.id_({"name": "IMAPClient", "version": "2.2.0"})  # 解决 Unsafe Login 问题
            log.info("[邮箱] 登录")
        except Exception as e:
            log.error("[邮箱] 登录 失败 {}".format(e))
            raise e

    def logout(self):
        """登出"""
        try:
            self.conn.logout()
            log.info("[邮箱] 登出")
        except Exception as e:
            log.error("[邮箱] 登出 失败 {}".format(e))
            raise e

    def list_folders(self, mailbox="INBOX"):
        """列出目录下所有文件夹"""
        try:
            mailboxes = [box for *_, box in self.conn.list_folders(mailbox)]
            log.info("[邮箱] 列出所有文件夹: {}".format(mailboxes))
            return mailboxes
        except Exception as e:
            log.error("[邮箱] 列出所有文件夹 失败 {}".format(e))
            raise e

    def select_folder(self, mailbox="INBOX"):
        """进入文件夹"""
        try:
            self.conn.select_folder(mailbox)
            log.info("[邮箱] 进入文件夹")
        except Exception as e:
            log.error("[邮箱] 进入文件夹 失败 {}".format(e))
            raise e

    def search(self, start_date=None, final_date=None, from_mail=None):
        """
        查找邮件
        :param start_date: 开始日期, 09-Sep-2021
        :param final_date: 结束日期
        :param from_mail: 来源邮箱
        :return: 符合条件的邮件 uid
        """
        try:
            search_criteria = []
            if start_date:
                search_criteria.extend(['SINCE', start_date])
            if final_date:
                search_criteria.extend(['BEFORE', final_date])
            if from_mail:
                search_criteria.extend(['FROM', from_mail])
            uid = self.conn.search(search_criteria)
            log.info("[邮箱] 查找邮件")
            return uid
        except Exception as e:
            log.error("[邮箱] 查找邮件 失败 {}".format(e))
            raise e


if __name__ == '__main__':
    config = {
        "host": "imap.163.com",
        "port": 993,  # 143 | 993
        "username": "xxx@163.com",
        "password": "xxx"
    }
    email = ImapMethod(**config)
    email.client()
    email.login()
    mbs = email.list_folders()
    email.select_folder(mbs[0])
    uid = email.search(from_mail="xxx@mail.com")
    print(uid)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aiden_SHI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值