如何从gmail imaplib阅读最新的电子邮件

问题描述

我试图阅读来自gmail的最新电子邮件,并提及了其他人发布的许多问题。这些解决方案都没有帮助我。我遇到的问题是读取最新邮件的10倍,是读取上次运行的旧电子邮件的2倍。 我正在为我的应用程序请求OTP,并且需要从最新的电子邮件中获取该OTP。 我的代码是

    def get_Account_OTP(self,email_type,language,otpfor):
    global conn,body,email_message,otpHeaderText
    if otpfor.lower() == "login":
        body = "Please verify your sign in attempt"
        otpHeaderText = "verification code is "
    elif otpfor.lower() == "createaccount":
        if language.lower() == "es":
            subject = "Adjunto"
            body = "Favor de verificar su correo electr=C3=B3nico"
            otpHeaderText = "Su c=C3=B3digo de verificaci=C3=B3n es "
        else:
            subject = "your email verification."
            body = "Please verify your email"
            otpHeaderText = "verification code is "
    if email_type == "gmail":
        conn = imaplib.IMAP4_SSL("imap.gmail.com",993)
        conn.login(self.gmail_username,self.gmail_password)
        conn.select('Inbox',readonly=False)
    data: list[Any]
    typ,data = conn.search(None,'(UNSEEN BODY "%s")' % body)
    optValue = ''
    counter = int(0)
    i = int(0)
    testResult = True
    num_of_messages = data[0].split()
    num_of_new_messages = data[0].split()
    while testResult:
         while num_of_new_messages == num_of_messages: #( I tried this while loop so the first time it reads all the old emails and run through this loop for 10 times if any new email is recieved)
             time.sleep(1)
             i = i + 1
             typ = ''
             data1: list[Any]
             typ,data1 = conn.search(None,'(UNSEEN BODY "%s")' % body)
             num_of_new_messages = data1[0].split()
             print("number of new messages at ",i,num_of_new_messages)
             if i == 10:
                 print("cannot find new message")
                 break
        if num_of_new_messages:
            print("New email found in " + str(counter) + " sec\s")
            testResult = False
        else:
            typ = ''
            data = []
            counter = counter + 1
            time.sleep(1)
            typ,'(UNSEEN BODY "%s")' % body)
            num_of_new_messages = data[0].split()
            print("new email in outer while loop",num_of_new_messages)
        if counter == 10:
            print("New email not found and waited for 10 secs before failing this test case")
            break

    if num_of_new_messages:
        latest_email_id = num_of_new_messages[-1] #(after searching on google I heard adding [-1] will retrieve the latest one,but still its not happening.
        typ,data = conn.fetch(latest_email_id,'(RFC822)')
        raw_email = data[0][1]
        raw_email_string = raw_email.decode('utf-8')
        email_message = str(email.message_from_string(raw_email_string))
        email_message_list = email_message.split('\n')
        RE_TIME_STAMP_PATTERN = re.compile((r'\d{6}'))
        
        for line in email_message_list:
            if otpHeaderText in line:
                self.OTP = re.findall(RE_TIME_STAMP_PATTERN,line)[0]
                optValue = self.OTP
                print(optValue)
                break
        else:
        print("No new emails found with the OTP code")

    return optValue

我不确定这里是什么问题。我是第一次使用该库,并确定我可能会丢失一些东西。我不确定是否需要等待10秒以上。

因此,每次我尝试在while循环中搜索电子邮件时,它仍然会尝试读取或不读取新邮件。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...