Resolving SMTPAuthenticationError in Python When Sending Emails via Gmail

Dec 01, 2025 · Programming · 13 views · 7.8

Keywords: Python | SMTPAuthenticationError | Gmail Security Settings

Abstract: This technical article provides an in-depth analysis of the SMTPAuthenticationError encountered when using Python's smtplib library to send emails through Gmail, particularly focusing on error code 534 and its accompanying messages. The article explains Google's security mechanisms that block login attempts from applications not using modern security standards. Two primary solutions are detailed: enabling "Less Secure App Access" in Google account settings and unlocking IP restrictions through Google's account unlock page. Through code examples and step-by-step guidance, developers can understand the root causes of the error and implement effective solutions, while also considering important security implications.

Problem Context and Error Analysis

When using Python's smtplib library to send emails through Gmail, developers frequently encounter the SMTPAuthenticationError, particularly with error code 534. This error is typically accompanied by the message: Please log in via your web browser and then try again. This indicates that Google's security mechanisms are blocking the login attempt.

Deep Analysis of Error Causes

Google's account security system blocks login requests from applications that don't meet modern security standards. According to Google's official documentation, this includes applications that don't use secure protocols like OAuth 2.0. When a Python script attempts to log in directly using username and password via smtplib, Google may identify this as a potential security risk.

The detailed information in the error response provides crucial clues: the <https://accounts.google.com/ContinueSignIn> link points to Google's login verification process, indicating that additional verification steps are required to complete authentication.

Solution 1: Enable Less Secure App Access

The most direct solution is to modify Google account security settings to allow "Less Secure App" access. This can be accomplished through the following steps:

  1. Visit Google account security settings: https://www.google.com/settings/security/lesssecureapps
  2. Sign in to your Google account
  3. Locate the "Less Secure App Access" option
  4. Select "Turn on" or "Allow"

After modifying these settings, rerun your Python script. Here's a complete code example:

import smtplib

# Configure Gmail account information
gmail_user = "your_email@gmail.com"
gmail_pwd = "your_password"
TO = "recipient@example.com"
SUBJECT = "Test Email Subject"
TEXT = "This is test email content sent via Python."

# Establish SMTP connection and send email
try:
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login(gmail_user, gmail_pwd)
    
    BODY = '\r\n'.join([
        'To: %s' % TO,
        'From: %s' % gmail_user,
        'Subject: %s' % SUBJECT,
        '',
        TEXT
    ])
    
    server.sendmail(gmail_user, [TO], BODY)
    print('Email sent successfully')
    server.quit()

except smtplib.SMTPAuthenticationError as e:
    print(f"Authentication error: {e}")
except Exception as e:
    print(f"Other error: {e}")

Solution 2: Remove IP Restrictions

If the problem persists after enabling less secure app access, Google may have temporarily blocked login attempts from your specific IP address. In this case, visit Google's account unlock page:

  1. Access from the same IP address experiencing the issue: https://accounts.google.com/DisplayUnlockCaptcha
  2. Follow the prompts to complete the verification process
  3. Retry sending the email

This approach is particularly useful when attempting to send emails from a new device or network location for the first time.

Security Considerations and Best Practices

While the above solutions resolve the SMTPAuthenticationError issue, developers should consider these security precautions:

Error Handling and Debugging Recommendations

When implementing email sending functionality, it's advisable to include comprehensive error handling:

def send_email_via_gmail(sender, password, recipient, subject, body):
    """Wrapper function for sending emails via Gmail"""
    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as server:
            server.ehlo()
            server.starttls()
            server.login(sender, password)
            
            message = f"Subject: {subject}\n\n{body}"
            server.sendmail(sender, recipient, message)
            return True
            
    except smtplib.SMTPAuthenticationError:
        print("Authentication failed. Please check account settings and password.")
        return False
    except Exception as e:
        print(f"Sending failed: {e}")
        return False

Through proper error handling and logging, developers can better diagnose and resolve issues encountered during email sending processes.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.