1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| import email import imaplib import re import time
def extract_emails(username, password, match_reg, group_index, timeout): imap_server = imaplib.IMAP4_SSL('imap-mail.outlook.com') imap_server.login(username, password) imap_server.select('INBOX')
start_time = time.time() while True: result, data = imap_server.search(None, 'ALL') if result != 'OK': print('搜索邮件失败') return
for num in data[0].split(): result, data = imap_server.fetch(num, '(RFC822)') if result != 'OK': print('获取邮件失败') return
raw_email = data[0][1] email_message = email.message_from_bytes(raw_email) for part in email_message.walk(): content_type = part.get_content_type() if content_type == 'text/plain': email_content = part.get_payload(decode=True).decode('utf-8') match = re.search(match_reg, email_content) if match: code = match.group(group_index) print('提取到的内容:', code) return code
if time.time() - start_time > timeout: print('超时') break
time.sleep(5)
imap_server.close() imap_server.logout()
if __name__ == '__main__': extract_emails("xxxxxxx@hotmail.com","xxxxxx",r"验证码[\s\S]*?(\d+)",1,10)
|