charlierguo / gmail

A Pythonic interface for Google Mail
MIT License
1.77k stars 386 forks source link

Using gmail inside a with #68

Open ffunenga opened 8 years ago

ffunenga commented 8 years ago

Something like this

class Gmail:

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def __enter__(self):
        # note: getpass might be better here, instead of keeping the pwd in memory
        self.g = gmail.login(self.username, self.password)
        return self.g

    def __exit__(self, *args, **kwds):
        try:
            print('logging out...')
            self.g.logout()
        except:
            raise

allows this

with Gmail(username, password) as conn:
    print('Reading all your emails from spam folder:')

    spam_box = conn.spam().mail(prefetch=True)
    n = conn.spam().count()

    for idx, email in enumerate(spam_box):
        print('fetching %d of %d...' % (idx + 1, n))

which would be nice to have implemented in the gmail package