Returned list created by looping over emails is becomes NoneType after being returned

47 Views Asked by At

I am making an email client, and I have a function called getmailbox. It retrieves the 50 most recent emails after the nth most recent email. It returns a list of lists containing the message id, subject, and sender of a message, for use in creating gui elements to display using tkinter.

I attempted to:

  • Open an ssl_imap connection to the imap server, using default ssl context

  • Login with the username and password provided earlier

  • Select a mailbox & search for messages

  • Reverse and slice the list, since it came in as oldest to newest

  • Loop through all the message ids and:

    • Fetch the message

    • Try to use the email module to parse the headers

    • Add it to the list of lists

  • Close mailbox, logout, return list.

  • Loop through list, to use info for gui

IMAP code:

def getmailbox(addr:str,pwd:str,strt:int=0,mailbox:str="INBOX"):
    context = create_default_context()
    with imaplib.IMAP4_SSL("outlook.office365.com",993,None,None,context) as sslimap:
        sslimap.login(addr,pwd)
        sslimap.select(mailbox)
        res, msgids = sslimap.search(None,'ALL')
        msgids = list(reversed(msgids[0].split()))[strt:strt+50]
        msgs_as_list = []
        for msgid in msgids:
            res1,obtuse_msg = sslimap.fetch(msgid,'(RFC822)')
            obtuse_msg = obtuse_msg[0][1]
            msg = email.message_from_bytes(obtuse_msg)
            try:
                sbj = str(make_header(decode_header(msg['Subject'])))
            except:
                sbj = "[INVALID]"
            try:
                fro = str(make_header(decode_header(msg['From'])))
            except:
                fro = "[INVALID]"
            msg_infolist = [sbj,fro,msgid.decode()]
            msgs_as_list = msgs_as_list + [msg_infolist]
        sslimap.close()
        sslimap.logout()
    return msgs_as_list

GUI Code (where IDLE says the problem is):

        def mailGui(strt,mailbox,nfstm):
            loadMoreButton.grid_forget()
            global r,pg,guimsgList
            if nfstm:    
                loadingLabel = tk.Label(msgframe,text="Loading...")
                loadingLabel.grid(row=r,column=0)
                win.update_idletasks()
            msgs=getmailbox(addr,pwd,strt,mailbox)
            if nfstm:
                loadingLabel.destroy()
            for i in msgs:
                msg_as_gui_inst = msgGui(msgframe,i[0],i[1],i[2])
                msg_as_gui_inst.grid(row=r,column=0)
                guimsgList = guimsgList + [msg_as_gui_inst]
                r += 1
            pg += 1
            loadMoreButton.grid(row=r,column=0)

Note: nfstm stands for "not the first time"

0

There are 0 best solutions below