I
I
ismail_20072021-03-23 18:50:39
Python
ismail_2007, 2021-03-23 18:50:39

How to fix this error imaplib.IMAP4.error: command LOGIN illegal in state LOGOUT, only allowed in states NONAUTH?

Hello! I'm trying to run two functions in parallel, one of which (get_mail_func( )) pulls unread messages from the mail, with an interval of 1 second. I get an error: imaplib.IMAP4.error: command LOGIN illegal in state LOGOUT, only allowed in states NONAUTH. It says that I am trying to log in, although I am authorized, although at the end of the function, I logged out. What is the problem?
Here is the class code:

class DialogMenu(tk.Toplevel):
    def __init__(self,user_name):
        super().__init__(root)
        self.user_name = user_name
        self.db = db
        self.get_mail_class_start = get_mail_class_start
        self.db.cur = self.db.conn.cursor()
        self.send_mail = Mail_class(user_name, smtplib.SMTP('smtp.gmail.com:587'))
        self.init_dialog()
        self.dialog_thread = threading.Thread(target = self.menu_thread(), args = ())
        self.dialog_thread.start()
 
    def retrieve_message_input(self):
        self.messsage_text = self.Message_Text.get(1.0, tk.END)
        self.send_mail.send_mail(self.messsage_text)
 
    def init_dialog(self):
        
        self.geometry('600x550')
        self.resizable(False,False)
        self['bg'] = '#2A3132'
        self.minsize(width = 900, height = 550) 
        self.title(f'Диалог с {self.user_name}')
 
        server = 'smtp.gmail.com:587'
        self.send_mail.start_client(server)

        
        self.Send_btn = tk.Button(self,text = '',padx=15,pady=12.5,bd=5,font=('Ubuntu',35),
                             bg = '#336B87',command = partial(self.dialog_db,self.user_name))
 
        self.Send_btn_sms = tk.Button(self,text = '➤',padx = 15,pady = 13,font = ('Ubuntu',35),bd = 5,
                                      bg = '#336B87', command = self.retrieve_message_input)
 
        self.Message_Text = tk.Text(self,width = 45,height = 5,bg='white',fg='black',font = 50)
        self.frame = tk.Frame(self)
        self.text = tk.Text(self.frame, width=85, height=22)
        self.scroll = tk.Scrollbar(self.frame, command=self.text.yview)
        self.scroll.pack(side=tk.RIGHT, fill=tk.Y)
        self.text.config(yscrollcommand=self.scroll.set)
        self.text.insert(tk.INSERT,("text" + '\n') * 50)
        self.text.configure(state='disabled')
 
        self.text.pack(side=tk.TOP) 
        self.text.place()
 
        self.frame.pack(side=tk.TOP)
        self.Send_btn.pack()
        self.Send_btn_sms.pack()
        self.Message_Text.pack()
 
        self.Send_btn.place(x = 670,y = 400)
        self.Send_btn_sms.place(x = 545, y = 400)
        self.Message_Text.place(x = 34,y = 400)
 
    def dialog_db(self, user_name):
        DialogDB(user_name)

    def menu_thread(self):
            self.after(True,get_mail_class_start.get_mail_func())

Here is the get_mail_func() function code
def __init__(self, mail):
        self.mail = mail
 
    def get_mail_func(self):
        my_file = open('text.txt', 'a+')
        (retcode, capabilities) = self.mail.login('******','*****')
        self.mail.list()
        self.mail.select('inbox')
        n=0
        (retcode, messages) = self.mail.search(None, '(UNSEEN)')
        if retcode == 'OK':
            for num in messages[0].split():
                n=n+1
                typ, data = self.mail.fetch(num,'(RFC822)')
                for response_part in data:
                    if isinstance(response_part, tuple):
                        original = email.message_from_bytes(response_part[1])
                        # print (original['From'])
                        # print (original['Subject'])
                        raw_email = data[0][1]
                        raw_email_string = raw_email.decode('utf-8')
                        email_message = email.message_from_string(raw_email_string)
                        typ, data = self.mail.store(num,'+FLAGS','\\Seen')
 
                        if email_message.is_multipart():
                            for payload in email_message.get_payload():
                                body = payload.get_payload(decode=True).decode('utf-8')
                                print(original['From'])
                                print(body)
                                my_file.write((f"\n {body}"))
                        
                        else:    
                            body = email_message.get_payload(decode=True).decode('utf-8')
                            print(original['From'])
                            print(body)      
                            my_file.write((f"\n {body}"))
            self.mail.close()
            self.mail.logout()
        
        self.mail.logout()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeniy _, 2021-03-23
@GeneD88

It seems like imap does not allow you to login, even after logout, on the same connection.
Therefore, you need to re-initialize self.mail before the next login.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question