New to Python, GMail SMTP error
Asked Answered
S

3

17

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')
Sensitive answered 29/10, 2012 at 4:6 Comment(1)
smptlib -> smtplibToadeater
C
33

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
Catamnesis answered 29/10, 2012 at 4:8 Comment(1)
Not to worry, even after 20 years working with SMTP, I still do that.Catamnesis
V
1

That misspelling occurred many times to me as well! One way to circumvent this "problem", is to use yagmail.

Jokes aside, I recently created yagmail to make it easier to send emails.

For example:

import yagmail
yag = yagmail.SMTP('[email protected]', 'password')
yag.send(contents = "Hello!")

It uses several shortenings here, for example when To is not defined, it will send a mail to the same email who registered on the server. Also the port and host are the default, which makes it very concise.

In fact, since it seems you want to close the connection immediately, you can even use this one-liner:

yagmail.SMTP('[email protected]', 'password').send(contents = "Hello!")

For security, you can keep your password in the keyring (see documentation) such that you do not have to keep your personal password in your scripts, very important! It'll even save you more precious screen-estate.

Going all-in with the package (@gmail.com is default), you can get away with the following:

yagmail.SMTP('user').send('', 'Hello!')

Good luck.

Veneration answered 18/4, 2015 at 18:43 Comment(1)
@sureshvv Thanks :) Hope it serves you well.Veneration
B
-1

from smtplib import SMTPExeption


exep smtplib.SMTPExeption

Bacardi answered 24/1, 2023 at 3:47 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Vincenty

© 2022 - 2024 — McMap. All rights reserved.