2026-07-15

How to read emails from gmail?

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

How to read emails from gmail?

Mastering Email Access: How to Read Emails from Gmail with Python (Solving Authentication Failures)

Connecting external services like Gmail to custom applications using Python's standard libraries (imaplib and smtplib) is a common requirement for data scraping or notification systems. However, as you have encountered, connecting to secure platforms like Google’s requires understanding their specific security protocols. The error [AUTHENTICATIONFAILED] Invalid credentials (Failure) is not usually an issue with the code logic itself, but rather a reflection of how modern services handle security, especially two-factor authentication (2FA).

As a senior developer, I can tell you that solving this involves moving beyond simple password usage and understanding the nuances of OAuth or application-specific credential management.

The Root Cause: Why AUTHENTICATIONFAILED Happens with Gmail

The reason your script fails at mail.login(FROM_EMAIL, FROM_PWD) is almost certainly related to Google’s security policies regarding account access. When you use a standard Gmail password for an external application, especially one using IMAP/SMTP protocols, Google often blocks the login attempt unless specific security conditions are met.

Here are the primary reasons this error occurs:

  1. 2-Factor Authentication (2FA): If 2FA is enabled on your Google account (which it should be), a simple password alone is insufficient for direct IMAP/POP3 access from an external script.
  2. App Passwords (The Recommended Fix): For applications that need programmatic access, Google strongly recommends generating an App Password. This is a unique, 16-character password specifically generated for that application, bypassing the need to use your main account password and allowing you to maintain strong security on your primary email.
  3. Security Restrictions: Direct login via standard IMAP/SMTP for personal accounts can be restricted by Google's security settings unless you have explicitly enabled less secure app access (which is deprecated).

Solution: Using App Passwords

To fix the AUTHENTICATIONFAILED error, you must generate an App Password from your Google Account Security settings. Use this generated 16-character password in place of your regular Gmail password when performing the mail.login() operation. This approach ensures that your application has necessary permissions without compromising your main account security.

IMAP and SMTP Ports Explained

You also asked about the ports you can use for these connections. Understanding the ports is crucial because they dictate whether you use secure (SSL/TLS) or insecure connections.

  • IMAP (Internet Message Access Protocol): This protocol is used to retrieve emails from a server.
    • Port: 993 (This uses SSL/TLS encryption, which is mandatory for modern security).
  • SMTP (Simple Mail Transfer Protocol): This protocol is used to send emails.
    • Port: 465 (Uses SSL/TLS) or 587 (Uses STARTTLS). Port 993 is standard for IMAP, so ensure your client uses the correct port for each protocol.

In your provided code snippet using imaplib, you should configure the connection to use these secure ports:

# Example setup reflecting secure IMAP connection
SMTP_SERVER = "smtp.gmail.com"
IMAP_PORT = 993  # Standard secure IMAP port

try:
    mail = imaplib.IMAP4_SSL(SMTP_SERVER, IMAP_PORT) # Specify both server and port here
    mail.login(FROM_EMAIL, FROM_PWD)
    # ... rest of the code
except imaplib.IMAP4.error as e:
    print(f"Login failed: {e}")

Refined Python Implementation for Reading Emails

The structure you employed is sound for reading email metadata using imaplib. The key refinement is ensuring the connection uses SSL/TLS correctly and handling the login securely. When building robust backend systems, like those often discussed in modern PHP frameworks such as Laravel, secure credential management is paramount; similar principles apply when dealing with external APIs and services.

Here is how you can refine your function to be more explicit about the secure connection:

import imaplib
import email
import traceback

ORG_EMAIL = "@gmail.com" 
FROM_EMAIL = "myemail" + ORG_EMAIL 
# IMPORTANT: Use the App Password here, not your regular login password!
FROM_PWD = "YOUR_GENERATED_APP_PASSWORD" 
SMTP_SERVER = "smtp.gmail.com"
IMAP_PORT = 993 # Secure IMAP Port

def read_email_from_gmail():
    try:
        # Connect using SSL/TLS for IMAP (Port 993)
        mail = imaplib.IMAP4_SSL(SMTP_SERVER, IMAP_PORT)
        
        print("Attempting to log in...")
        mail.login(FROM_EMAIL, FROM_PWD)
        print("Login successful!")

        mail.select('inbox')

        # Search for all mail (use 'ALL' or specific search criteria)
        data = mail.search(None, 'ALL')
        mail_ids = data[1]
        id_list = mail_ids[0].split()   
        
        if not id_list:
            print("No emails found in the inbox.")
            return

        # Process the latest email (example)
        latest_email_id = int(id_list[-1])
        
        # Fetch the specific email data
        data = mail.fetch(str(latest_email_id), '(RFC822)')
        
        for response_part in data:
            if response_part:
                # Parse the raw email content
                msg = email.message_from_string(response_part[0][1],'utf-8')
                email_subject = msg['subject']
                email_from = msg['from']
                print('--- New Email Found ---')
                print('From : ' + email_from + '\n')
                print('Subject : ' + email_subject + '\n')

    except imaplib.IMAP4.error as e:
        print(f"\n[IMAP ERROR] Authentication or connection failed: {e}")
        print("Please double-check your App Password and account settings.")
    except Exception as e:
        traceback.print_exc() 
        print(f"\nAn unexpected error occurred: {e}")

read_email_from_gmail()

Conclusion

Reading emails programmatically is a powerful capability, but it demands respect for security protocols. The failure you encountered stems from the shift in how major providers like Google handle authentication. By implementing App Passwords and correctly utilizing secure ports (like IMAP on port 993), you can establish a stable, secure connection. Always treat credentials as sensitive data; this practice of securing access is fundamental to building reliable applications, whether you are developing custom scripts or large-scale systems relying on robust backend logic, much like the architecture promoted by companies focusing on modern framework development.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.