I want to write error handling for wen a user would input a wrong password to my script. I keep changing the code after the except statement, but I can't find out what the right code for the error is. Am I missing something?
import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.gmail.com')
username = raw_input('USERNAME (email):')
password = raw_input('PASSWORD: ')
try:
mail.login(username, password)
print "Logged in as %r !" % username
except:
imaplib.error
print "Log in failed."
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
fromWho = raw_input('FROM:')
result, data = mail.uid('search', None, '(FROM fromWho)')
latest_email_uid = data[0].split()[-1]
result, data = mail.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = data[0][1]
print raw_email
If you want to catch a certain exception, the exception name in try...except
clause in Python should be written after except
keyword:
try:
mail.login(username, password)
print "Logged in as %r !" % username
except imaplib.IMAP4.error:
print "Log in failed."
Note that I changed exception name to imaplib.IMAP4.error
. That's not obvious, but you can find the proper name of the exception by looking in the source code for imaplib
.
I am not sure if this is considered good practice, but the mail
object is generated from imaplib.IMAP4
and can be used.
Using the sample code above:
...
except mail.error:
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With