zmail好用、但有些场景不支持、比如gmail、yandex邮箱不支持搜索功能、此时需要使用imap了、
imap获取邮件信息代码
import imaplib, mailparser, traceback
def get_mail(user_name=None, pwd=None):
"""
hdfc bank获取otp
@param user_name:
@param pwd:
@return: None
"""
host = 'imap.gmail.com'
port = '993'
try:
imap = imaplib.IMAP4_SSL(host=host, port=port)
imap.login(user=user_name, password=pwd)
sender = 'XXXXXXXXXXXXXXx' # 发件人
sub = 'XXXXXXXXXXXXXXXXXX' # 主题
imap.select('INBOX')
_, list_data = imap.search(None, f'(FROM "{sender}" SUBJECT "{sub}")') # 过滤器 也支持文本搜索
for msg_id in list_data[0].split()[::-1]: # 倒序后最新的在前
is_success_, mail_list = imap.fetch(msg_id, 'BODY[]') # 获取最新邮件
raw_msg = mail_list[0][1] # index0 下 index1 为数据
mail = mailparser.parse_from_bytes(raw_msg) # 解析邮件
html_str = mail.text_html[0] # 获取邮件信息
mail_time = mail.date
print(f'html_str | {html_str}')
print(f'mail_time | {mail_time}')
imap.store(msg_id, '+FLAGS', '\\Deleted') # 删除邮件、
imap.close()
imap.logout()
return None
except Exception:
print(f'{traceback.format_exc()}')
return None