接收邮件
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)
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"})
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,
"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)