python imaplib - gmail cannot be accessed

65 Views Asked by At

I am trying to access and read emails from my gmail account using a python script and imaplib, but whenever I run, I receive this message from the terminal: imaplib.error: b'[AUTHENTICATIONFAILED] Invalid credentials (Failure)'

I've tried looking online everywhere, even on StackOverflow itself, and all if not most of the ways I found were outdated, or simply didn't work. I'm simply trying to login to my gmail through python, and since Google disabled the less secure access for third party apps, I can't fine the solution. Can someone here help me?

import imaplib
import email


username = '[email protected]'
password = 'TheCorrectPassword'

mail = imaplib.IMAP4_SSL("imap.gmail.com")


mail.login(username, password)

This is my code. I have boiled it down and simplified it to the root cause, which is the login part.

1

There are 1 best solutions below

0
Mahesh P On

You have to use app password instead of your Gmail password. To generate an app password, you need to set up 2FA for your account first.