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