Encountering SMTP error while learning Python email sending

Hi everyone! I’m new to Python and trying to send emails using Gmail SMTP. I wrote a simple function to email myself, but I’m running into an error. It says:

NameError: name 'SMTPException' is not defined

I’m not sure what’s wrong with my code. Can anyone help me figure it out? Here’s what I’ve got so far:

from email_sender import EmailSender

sender_address = '[email protected]'
recipient_list = ['[email protected]']
email_content = 'Test message'

try:
    email = EmailSender('smtp.gmail.com', 587)
    email.start_connection()
    email.secure_connection()
    email.authenticate(sender_address, 'mypassword')
    email.send(sender_address, recipient_list, email_content)
    email.end_connection()
except EmailError:
    print('Failed to send email')

Any tips or suggestions would be really appreciated. Thanks!

I’ve run into this issue before. The problem lies in your exception handling. You’re catching an EmailError, but that’s not a standard Python exception. Instead, you should catch the SMTPException.

Here’s how you can modify your code:

from smtplib import SMTPException
from email_sender import EmailSender

# ... your existing code ...

try:
    # ... your existing try block ...
except SMTPException as e:
    print(f'Failed to send email: {str(e)}')

This change should resolve the NameError you’re encountering. Also, ensure you’re using an app-specific password for Gmail, as they’ve tightened security recently. Let me know if you need any further clarification.

I’ve encountered similar issues when working with SMTP in Python. The error you’re seeing suggests that you haven’t imported the SMTPException class. Try adding this import at the top of your script:

from smtplib import SMTPException

Also, I noticed you’re using a custom EmailSender class. Make sure it’s properly handling exceptions. If you’re just starting out, it might be easier to use Python’s built-in smtplib module directly. Here’s a simplified version that might work for you:

import smtplib
from email.mime.text import MIMEText

sender = '[email protected]'
recipient = '[email protected]'
password = 'your_app_password'

msg = MIMEText('Test message')
msg['Subject'] = 'Test Subject'
msg['From'] = sender
msg['To'] = recipient

try:
    with smtplib.SMTP('smtp.gmail.com', 587) as server:
        server.starttls()
        server.login(sender, password)
        server.send_message(msg)
    print('Email sent successfully')
except Exception as e:
    print(f'Failed to send email: {str(e)}')

Remember to use an app password instead of your regular Gmail password for security. Hope this helps!

hey there liamj, looks like u forgot to import SMTPException. just add this at the top:

from smtplib import SMTPException

also, make sure ur using an app password for gmail, not ur regular one. they changed that recently. good luck with ur project!