Trouble Bucket
Trouble Bucket

Reputation: 333

How to write a function that that generates the login for a mailbox with imap_tools?

I created a helper function that logs into a mailbox.

import imap_tools

def mailbox_login():
    try:
        with imap_tools.MailBoxUnencrypted(ENV["IMAP4_FQDN"]).login(
            ENV["RECEIVING_EMAIL_USER"], ENV["RECEIVING_EMAIL_PASSWORD"]
        ) as mailbox:
            print("Successfully logged into the mailbox.")
            return mailbox
    except imap_tools.MailboxLoginError as error:
        print(f"CRITICAL: Failed to login to the mailbox: {error}")

Another function requires a mailbox connection.

def email_count():
    """
    Get all emails from the mail server via IMAP
    """
    msgs = []
    mailbox = mailbox_login()
    for msg in mailbox.fetch():
        msgs.append(msg)
    return msgs

When I run email_count(), I get the following error:

imaplib.IMAP4.error: command SEARCH illegal in state LOGOUT, only allowed in states SELECTED

As soon as I leave the scope of the with statement, it logs out of the mailbox. Is there any way to maintain the connection after leaving mailbox_login()?

Upvotes: 0

Views: 134

Answers (2)

Vladimir
Vladimir

Reputation: 6716

Try to read about context manager - with

https://docs.python.org/3/reference/compound_stmts.html#the-with-statement

Upvotes: 0

n4zgu1
n4zgu1

Reputation: 11

You need to select a mailbox after connecting successfully to the IMAP-Server. Use

mailbox.select()

after connecting and before search.

Upvotes: 0

Related Questions