Python beginner facing SMTP exception error with Gmail

I’m trying to create a basic email sending script using Python and Gmail’s SMTP server, but I keep running into an issue.

Every time I run my code, I get this error message:

NameError: name 'SMTPException' is not defined

I’m not sure what I’m doing wrong here. Could someone help me figure out what’s causing this problem?

Here’s my current code:

import smtplib

email_from = "[email protected]"
email_to = ["[email protected]"]
text_message = "Test message!"

try:
    smtp_server = smtplib.SMTP('smtp.gmail.com', 587)
    smtp_server.ehlo()
    smtp_server.starttls()
    smtp_server.ehlo()
    smtp_server.login(email_from, 'mypassword')
    smtp_server.sendmail(email_from, email_to, text_message)
    smtp_server.quit()
except SMTPException:
    print('Something went wrong')

Any help would be appreciated!

Your exception handling is incorrect because SMTPException is not defined in your current scope. You should access it through the smtplib module. Modify your except statement to except smtplib.SMTPException:. I encountered a similar issue when I was setting up automated email reports. Additionally, due to security changes, you’ll need to use an app password instead of your regular Gmail password. This can be generated in your Google account’s security settings.

quick fix - just catch Exception instead of SMTPException if u wanna avoid import issues. it worked for me when i faced this last week. tho, importing it properly like others said is the way to go, but this gets ur code running quick.

You need to import SMTPException separately from smtplib. When you just do import smtplib, you only get the main SMTP class - the exception classes aren’t included automatically. Change your import to from smtplib import SMTP, SMTPException or add from smtplib import SMTPException after your current import. I hit this exact same problem when I started doing email automation in Python. The error’s actually pretty clear once you know what’s happening - Python can’t find SMTPException because it’s not in your namespace.