使用Python和Selenium删除单个选定的Outlook邮件

eqqqjvef  于 2023-06-20  发布在  Python
关注(0)|答案(2)|浏览(111)

我有一段代码,可以在outlook主收件箱中轮询一封2因素身份验证电子邮件,找到一个字符串,然后将其复制到网页上,然后按enter。
我想在此之后删除电子邮件。
我不知道我在代码中的什么地方出错了。
我没有编写原始的python,并打算修改它以查找最新的消息并使用该消息而不是len(messages)==1条件,但我仍然希望在完成后删除消息。

#Part 2: Retreive passcode from email for authentication
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
inbox = mapi.GetDefaultFolder(6)
received_dt = datetime.now() - timedelta(minutes=5)
received_dt = received_dt.strftime('%m/%d/%Y %H:%M %p')
delay = 15 #seconds
waitloop = 1
passcodefound = 0
while passcodefound == 1:
    print ("Authentication email found.")
    break # it will break from the loop once the specific element will be present.
else:
    print("waiting for " + str(delay)+ " seconds.")
    time.sleep(delay)
    messages = inbox.Items
    messages = messages.Restrict("[ReceivedTime] >= '" + received_dt + "'")
    messages = messages.Restrict("[SenderEmailAddress] = '  '")
    messages = messages.Restrict("[Subject] = ' '")
    print("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.")
            passcodefound = 1
            passcode_field=driver.find_element(By.ID," ")
            passcode_field.clear()
            passcode_field.send_keys( )
            submit_button=driver.find_element(By.ID,"otpSubmitButton")
            submit_button.click()
            **message.Delete**
            break
    else:
        waitloop = waitloop+1
        total_wait_time = waitloop * delay
        print ("Authentication email not found. Wait time total = " + str(total_wait_time) + " seconds. Waiting for "+str(delay)+" seconds and trying again")

我移动了消息。删除之前的行到打印后(“2 Factor Authentication email found and processed.”),结果相同。
我取消缩进消息。删除并打断行,我得到了一个错误,因为我在循环之外打断了消息。删除并注解掉了中断,没有错误,但消息没有被删除。

2uluyalo

2uluyalo1#

首先,你不能通过多次调用Restrict来进行限制--只调用Restrict一次,然后用"AND"运算符将所有3个条件连接起来:

messages = messages.Restrict("[ReceivedTime] >= '" + received_dt + "' AND " & _
                             "[SenderEmailAddress] = '  ' AND " & _
                             "[Subject] = ' '")

其次,如果您仍然希望删除所有消息,即使发现了多个消息,请将if len(messages) == 1:条件更改为if len(messages) > 0:

yshpjwxd

yshpjwxd2#

message.Delete()
import win32com.client    

def outlook_item(messages):
    if messages.Count > 0:
        print(messages.Count)
        for message in reversed(range(messages.Count, 0, -1)):
            print(message)
            message.Delete()
    else:
        print("Nothing selected.")


if __name__ == '__main__':
    olApp = win32com.client.Dispatch("outlook.Application")
    items = olApp.ActiveExplorer().Selection
    outlook_item(items)

相关问题