(Python 3) imaplib logins from .txt file

126 views Asked by At

In a file called "emails.txt" I have few accounts in this format - email:pw. I've already done split, and everything works perfect, but only if there is only one account:pw in the list.

If I put 2 or more, I'm getting Login failed on first account.

Here's code (login and function, not included)

with open('emails.txt') as emails:
    for line in emails:

        EMAIL_ACCOUNT = line.split(":", -2)[-2]
        PASSWORD = line.split(":", 1)[1]

        print(PASSWORD)

        EMAIL_FOLDER = "INBOX"

        M = imaplib.IMAP4_SSL('imap.gmx.com')

        try:
            rv, data = M.login(EMAIL_ACCOUNT, PASSWORD)
        except imaplib.IMAP4.error:
            print("Failed!" + EMAIL_ACCOUNT)
            sys.exit(1)
            time.sleep()
        M.logout()

What should I do, to make it:

    1. Login from first account from list, and do the job
    1. Login from second account from list, and do the job etc.
1

There are 1 answers

1
Gassa On BEST ANSWER

Since you don't supply an example emails.txt file, I'll resort to guessing what actually happens. Sorry if this turns out to be wrong!

Note that the lines in for line in emails: do include the trailing line break. Perhaps you don't insert a line break after the end of the last line when editing (which can cause problems with automation later, but that's beside the point).

So, when you have a file email1:password1 (no line break after the password), everything is fine. When you instead have a file email1:password1\nemail2:password2 (here, \n is the line break), your program sees the password for the first email as password1\n instead of just password1.

One way to get the trailing newline character removed is to use strip() function, like this: PASSWORD = line.split(":", 1)[1].strip().


Also, it can be a good habit to follow the definition "a line is something which ends with a line break", i.e., add a line break after the last line, too. This can achieve uniformity, simplify automation, and remove corner cases. But I digress.