Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle errors with imaplib in Python

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
like image 460
metersk Avatar asked Sep 12 '13 02:09

metersk


2 Answers

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.

like image 99
Andrey Sobolev Avatar answered Oct 17 '22 17:10

Andrey Sobolev


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: ...

like image 45
Todd S Avatar answered Oct 17 '22 16:10

Todd S