使用Python+win32com操作Outlook删除指定双因素认证邮件失败的问题排查求助
使用Python+win32com操作Outlook删除指定双因素认证邮件失败的问题排查求助
各位大佬好,我遇到个棘手的问题,想请大家帮忙看看:
我写了一段Python代码,功能是轮询Outlook主收件箱里的双因素认证邮件,提取里面的6位验证码,自动填入网页并提交。现在我想在完成这些操作后把这封认证邮件删掉,但试了好几种写法都没成功,实在找不到问题出在哪了。
另外提一句,我原本还打算修改这段代码——现在的判断条件是len(messages)==1,我想改成直接取最新的那封邮件来处理,但不管逻辑怎么改,删除邮件这个需求是一定要实现的。
下面是我的代码片段(部分敏感信息已留空):
# Part 2: Retrieve passcode from email for authentication import win32com.client import datetime from datetime import timedelta import time import re from selenium.webdriver.common.by import By outlook = win32com.client.Dispatch('outlook.application') mapi = outlook.GetNamespace("MAPI") inbox = mapi.GetDefaultFolder(6) received_dt = datetime.datetime.now() - timedelta(minutes=5) received_dt = received_dt.strftime('%m/%d/%Y %H:%M %p') delay = 15 # seconds waitloop = 1 passcodefound = 0 # 原代码这里写的是passcodefound ==1,应该是笔误,否则循环根本不会执行 while passcodefound == 0: messages = inbox.Items messages = messages.Restrict("[ReceivedTime] >= '" + received_dt + "'") messages = messages.Restrict("[SenderEmailAddress] = ' '") messages = messages.Restrict("[Subject] = ' '") print(f"filtered inbox, {str(len(messages))} found.") if len(messages) == 1: for message in messages: text = message.Body CodeRegexVariable = re.compile(r'(\d\d\d\d\d\d)') code = CodeRegexVariable.search(str(text)) answer = code.group() print(answer) print("2 Factor Authentication email found and processed.") # 填充验证码并提交 passcode_field = driver.find_element(By.ID," ") passcode_field.clear() passcode_field.send_keys(answer) # 原代码这里是空的,推测应该传入提取到的验证码 submit_button = driver.find_element(By.ID,"otpSubmitButton") submit_button.click() # 尝试删除邮件 message.Delete() passcodefound = 1 break else: waitloop += 1 total_wait_time = waitloop * delay print(f"Authentication email not found. Wait time total = {str(total_wait_time)} seconds. Waiting for {str(delay)} seconds and trying again") time.sleep(delay)
我已经尝试过这些调整,但都没解决问题:
- 把
message.Delete()移到print("2 Factor Authentication email found and processed.")后面,结果还是删不掉邮件; - 取消
message.Delete()和break的缩进,结果直接报错“break outside loop”; - 只取消
message.Delete()的缩进并注释掉break,虽然没报错,但邮件依然没被删除。
有没有大佬能帮我看看哪里出问题了?或者有没有更可靠的删除Outlook邮件的方法?
备注:内容来源于stack exchange,提问作者Chris Sabol




