Hello, new coder here :-)

I've been working on one of my first scripts, an SMTP script for sending mail with Gmail.

It works and all, but I wan't to have an "if" the login to the server failed, it would print and message saying so and return to the beginning.

gname = raw_input("Username: ")
gpass = getpass.getpass("Password: ")

server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(gname,gpass)

The first part is where the user inputs the login data, and then it continues the to try and log onto the Gmail account. If at first I spell my username incorrectly, or type the wrong password, I get "SMTPAuthenticationError".

So what I'm trying to produce is something like this:

if smtplib.SMTPAuthenticationError:
    print "Error! Wrong password or username."
else:
    print "Logged in as ", gname

But it doesn't work (mainly because I don't know how to "if" it), and I haven't found any specific information that would point me in the right direction for an solution.

Is there anyone that are willing to help me? Not necessary give the solution in text, but like give me some hints.

Thanks in advance!

Recommended Answers

All 10 Replies

Instead of using If to handle errors you need to use the Try and Except statement.

Here is your code using those.

import getpass, smtplib

gname = raw_input("Username: ")
gpass = getpass.getpass("Password: ")

try: #Try to execute the code between try: and except:
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(gname,gpass) #<-- SMTPAuthenicationError is raised here.
    #Now Python will look for an Except clause that handles that specific error, skipping over the rest of the Try clause. 
    #Which is printing that we are logged in, which we aren't!

    print "Logged in as ", gname  

except smtplib.SMTPAuthenticationError:        #Found it! 
    print "Error! Wrong password or username." #Huzzah!

From the Python documentation:
"The try statement works as follows.

* First, the try clause (the statement(s) between the try and except keywords) is executed.

* If no exception occurs, the except clause is skipped and execution of the try statement is finished.

* If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement."

Here's a link to the page all about errors and exceptions.
http://docs.python.org/tutorial/errors.html

I apologize if I make no sense at all. I'm a terrible teacher. :P

Thank you, I've found something to play with!

Will report back later when I've found the proper solution.

SUNTOM
WILDBAMABOY just pointed you the way. That is how python deals with error checking.

you need to try and except.

Just like c++ try catch thing.

;)

I've manged to get what I wanted using try, except and defining a function to restart the script.

Is there anything else that can be done, like in a more professional way (we newbies tend to use methods thats considered unprofessional to get things done)?

#!/usr/bin/python
#Terminal Gmail, version 1.2
#Copyright (c) 2010 by Tom Arne Sundtjonn

#imports the required modules
import smtplib, getpass, sys, os

print "\nTerminal Gmail 1.0\n"

#asks the user for login information
gname = raw_input("Username: ")
gpass = getpass.getpass("Password: ")

print ""

#defining the restart function
def restart_program():
    python = sys.executable
    os.execl(python, python, * sys.argv)

#now the script will try to log in
while True:
    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(gname,gpass)

        #if you succeeded, the script will print this message
        print "Logged in as", gname

        print ""

        #the script now asks for the adress, subject etc
        gadr = raw_input("To: ")
        gsub = raw_input("Subject: ")
        gmail = raw_input("Message: ")

        #this will give the user an option to cancel the mail
        raw_input("\nPress ENTER to send the mail or CTRL-C to abort...")

        #this tells the script where each input should be (subject, toadress etc)
        gmsg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nMessage: %s\r\n" % (gname, gadr, gsub, gmail)

        #now it connects to the smtp server and sends the mail
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(gname,gpass)
        server.sendmail(gname, gadr, gmsg+gmail)
        server.quit()

        #if the script was successful it will print this message
        print "\nThe mail has been sent to", gadr
        print ""

#if you failed to type the correct login information, the script jumps down here
    except smtplib.SMTPAuthenticationError:
        print "\nError! Wrong password or username."
        restart_program() #this is the function that restarts the script so you can try again

#if you cancel the script with ctrl-c
    except KeyboardInterrupt:
        print "\nLogged off."
        print ""
        exit(1)

#if you cancel the script with ctrl-d
    except EOFError:
        print "\nLogged off."
        print ""
        exit(1)

Thanks for the help - now I'll try to add attachments.

Why do you log-in 2 times???? line 28 , 52

optimise your code well cos it may lead to bug.

once you login, the connection stays until the programe exists.
Creating server object 2 times means 2 different object.
Your code can be small and effective if you work on that.

Besides all that, i think you are not doing bad buddy.
;)

Because if I remove the second login part, before server.sendmail, I get the following error.

SMTPSenderRefused: (530, '5.5.1 Authentication Required)

And only when I use server.login once more, I get passed the error - any advice regarding that?

Thanks for your reply!

Because if I remove the second login part, before server.sendmail, I get the following error.

And only when I use server.login once more, I get passed the error - any advice regarding that?

Thanks for your reply!

I think you should remove lines 47 to 51 included.

yep 47-51 will do the trick friend. ;)

Thanks, that did the trick!

Regarding the rest of the code, is it decent?

as much as i know for now. YEPEEEEE
;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.