Python 实现登录并提取outlook邮箱的最新验证码

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
# by GPT
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)

taskkill /f /im msrdc.exe