how to fix imap in python

Viewed 24

a few days ago i'm using a python module to make listing on outlook mail and scraping a specific mail from specific address everything was worked well until last day iam getting error afer few second after each running i trayed to change email or password or check pop and imap connection on mail setting but still got same error pls any help will be welcome because iam newbie

python module:

import time
from email.policy import default
from itertools import chain
import email
import imaplib
import base64
import sys

imap_ssl_host = 'outlook.office365.com'  # imap.mail.yahoo.com
imap_ssl_port = 993
username = 'EMAIL@outlook.fr'
password = 'Aazert'

# Restrict mail search. Be very specific.
# Machine should be very selective to receive messages.
criteria ={
    'FROM':    'donotreply@COMPANY.com',
    'SUBJECT': "*",
    'BODY':    '*',
}


uid_max = 0


def search_string(uid_max, criteria):
    c = list(map(lambda t: (t[0], '"'+str(t[1])+'"'), criteria.items())) + [('UID', '%d:*' % (uid_max+1))]
    return '(%s)' % ' '.join(chain(*c))
    # Produce search string in IMAP format:
    #   e.g. (FROM "me@gmail.com" SUBJECT "abcde" BODY "123456789" UID 9999:*)


def get_first_text_block(msg):
    type = msg.get_content_maintype()

    if type == 'multipart':
        for part in msg.get_payload():
            if part.get_content_maintype() == 'text':
                return part.get_payload()
    elif type == 'text':
        return msg.get_payload()


server = imaplib.IMAP4_SSL(imap_ssl_host, imap_ssl_port)
server.login(username, password)
server.select('INBOX')

result, data = server.uid('search', None, search_string(uid_max, criteria))

uids = [int(s) for s in data[0].split()]
if uids:
    uid_max = max(uids)
    # Initialize `uid_max`. Any UID less than or equal to `uid_max` will be ignored subsequently.

server.logout()


# Keep checking messages ...
# I don't like using IDLE because Yahoo does not support it.
while 1:
    # Have to login/logout each time because that's the only way to get fresh results.

    server = imaplib.IMAP4_SSL(imap_ssl_host, imap_ssl_port)
    server.login(username, password)
    server.select('INBOX')

    result, data = server.uid('search', None, search_string(uid_max, criteria))

    uids = [int(s) for s in data[0].split()]
    for uid in uids:
        # Have to check again because Gmail sometimes does not obey UID criterion.
        if uid > uid_max:
            result, data = server.uid('fetch', str(uid), 'BODY.PEEK[1]')    
              #result, data = server.uid('fetch', uid, '(RFC822)')  # fetch entire message
           
            msg = email.message_from_bytes(data[0][1], policy=default)

            uid_max = uid
        
            text = get_first_text_block(msg)
            
            print ('New message :::::::::::::::::::::')
            #print (text.split("unique est")[1].split()[0].replace(".", ""))
            yourstring= text
            
            ijij = base64.b64decode(yourstring.encode("utf8")).decode("utf8")
            substring = "unique est"
            fullstring= ijij   
            if substring in fullstring:
             print (ijij.split("unique est")[1].split()[0].replace(".", "") )
             myText = open(r'C:\Users\Administrator\Desktop\otp\otp4.txt','w')
             myString = ijij.split("unique est")[1].split()[0].replace(".", "")
             myText.write(myString)
             myText.close()
            
            else:
             print (ijij)
             print (ijij.split("Your OTP is")[1].split()[0].replace(".", "") )

             myText = open(r'C:\Users\Administrator\Desktop\otp\otp4.txt','w')
             myString = ijij.split("Your OTP is")[1].split()[0].replace(".", "")
             myText.write(myString)
             myText.close()
             
    server.logout()
    time.sleep(1)

error:

  Traceback (most recent call last):
      File "C:\Users\Administrator\Desktop\fs\YOU3.py", line 65, in <module>
        server.select('INBOX')
      File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\imaplib.py", line 756, in select
        typ, dat = self._simple_command(name, mailbox)
      File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\imaplib.py", line 1230, in _simple_command
        return self._command_complete(name, self._command(name, *args))
      File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\imaplib.py", line 1055, in _command_complete
        raise self.error('%s command error: %s %s' % (name, typ, data))
    imaplib.IMAP4.error: SELECT command error: BAD [b'User is authenticated but not connected.']
0 Answers
Related