Home >Backend Development >Python Tutorial >How to Solve the 'SMTP AUTH extension not supported by server' Error When Sending Emails with Python and Gmail?

How to Solve the 'SMTP AUTH extension not supported by server' Error When Sending Emails with Python and Gmail?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-03 17:15:121077browse

How to Solve the

Sending Emails with Gmail via Python

Sending emails through Gmail using Python can be a straightforward task, but occasionally you may encounter errors. One such error is "SMTP AUTH extension not supported by server." This arises when you try to log in to your Gmail account using the login() method.

To resolve this issue, a modification to your Python script is necessary. Replace the code that attempts to invoke the login() method with the following:

import smtplib

def send_email(user, pwd, recipient, subject, body):
  FROM = user
  TO = recipient if isinstance(recipient, list) else [recipient]
  SUBJECT = subject
  TEXT = body

  # Prepare actual message
  message = """From: %s\nTo: %s\nSubject: %s\n\n%s
  """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
  try:
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.login(user, pwd)
    server.sendmail(FROM, TO, message)
    server.close()
    print('successfully sent the mail')
  except:
    print("failed to send mail")

Alternatively, you can opt to use Port 465 by implementing an SMTP_SSL object:

# SMTP_SSL Example
server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server_ssl.ehlo() # optional, called by login()
server_ssl.login(gmail_user, gmail_pwd)
# ssl server doesn't support or need tls, so don't call server_ssl.starttls()
server_ssl.sendmail(FROM, TO, message)
#server_ssl.quit()
server_ssl.close()
print('successfully sent the mail')

The above is the detailed content of How to Solve the 'SMTP AUTH extension not supported by server' Error When Sending Emails with Python and Gmail?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn