Search code examples
pythonsmtpgmailsmtplib

New to Python, GMail SMTP error


I am writing a simple sendmail function to myself and I keep getting this error:

NameError: name 'SMTPException' is not defined

What is wrong with my code? Any suggestions?

import smtplib

sender = "[email protected]"
receiver = ["[email protected]"]
message = "Hello!"

try:
    session = smptlib.SMTP('smtp.gmail.com',587)
    session.ehlo()
    session.starttls()
    session.ehlo()
    session.login(sender,'password')
    session.sendmail(sender,receiver,message)
    session.quit()
except SMTPException:
    print('Error')

Solution

  • In Python, you will need to fully qualify the name by prefixing it with its module:

    except smtplib.SMTPException:
    

    This is true unless you specifically import the unqualified name (but I wouldn't recommend doing this for your program, just showing what's possible):

    from smtplib import SMTPException