简体   繁体   中英

HOW TO FIX IMAP IN PYTHON

IAM USING PYTHON CODE TO SCRAP SPICIFIC EMAIL EVERY THING WAS FINE THE CODE WORKED GOOD UNTIL TODAY THAT GIVE ME AN ERROR AFTER FEW MINUTES OF RUNNING EVERY TIME. I TRYED TO CHANGE EMAIL AND ACTIVE POP AND IMAP CONNECTION FROM THE EMAIL SETING BUT THE SAME ERROR WAS GIVEN PLS HOW TO FIX THIS KIND OF ERROR CODE USED

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)

THE ERROR GIVEN

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\vfs\YOUSFI ASMA 3.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.']

You're using a freemail provider and busylooping. Change the 2 to about 7200 and you'll have no problems, or change to an email provider that you pay.

As long as you use resources and they pay, they're going to want to limit your resource use.

(Oh, and your keyboard is defective. The shift key seems to be stuck.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM