Python Gmail

simplest way to read gmail with python



    There are several ways to read Gmail emails from Python but I found this one the simplest one. Imap-tools is a high-level library for working with email by IMAP.

  • Basic message operations: fetch, uids, numbers
  • Parsed email message attributes
  • Query builder for search criteria
  • Actions with emails: copy, delete, flag, move, append
  • Actions with folders: list, set, get, create, exists, rename, subscribe, delete, status
  • IDLE commands: start, poll, stop, wait
  • Exceptions on failed IMAP operations
  • No external dependencies, tested

This is useful when you want to integrate mail functionality into your app with simplicity in mind. The first thing to do is to install the imap-tools library with pip and that's the only dependency to install.

 

pip install imap-tools

 

    The most basic example from Github repo:

 

from imap_tools import MailBox, AND

"""
Get date, subject and body len of all emails from INBOX folder
1. MailBox()
    Create IMAP client, the socket is created here
    
2. mailbox.login()
    Login to mailbox account
    It supports context manager, so you do not need to call logout() in this example
    Select INBOX folder, cause login initial_folder arg = 'INBOX' by default (set folder may be disabled with None)
    
3. mailbox.fetch()
    First searches email nums by criteria in current folder, then fetch and yields MailMessage
    criteria arg = 'ALL' by default
    Current folder is 'INBOX' (set on login)
    Fetch each message separately per N commands, cause bulk arg = False by default
    Mark each fetched email as seen, cause fetch mark_seen arg = True by default
    
4. print
    msg variable is MailMessage instance
    msg.date - email data, converted to datetime.date
    msg.subject - email subject, utf8 str
    msg.text - email plain text content, utf8 str
    msg.html - email html content, utf8 str
"""
with MailBox('imap.mail.com').login('test@mail.com', 'pwd') as mailbox:
    for msg in mailbox.fetch():
        print(msg.date, msg.subject, len(msg.text or msg.html))

 

    Equivalent verbose version:

 

from imap_tools import MailBox, AND

mailbox = MailBox('imap.mail.com')
mailbox.login('test@mail.com', 'pwd', 'INBOX') # or use mailbox.folder.set instead initial_folder arg
for msg in mailbox.fetch(AND(all=True)):
    print(msg.date, msg.subject, len(msg.text or msg.html))
mailbox.logout()

 

    We need to replace 'test@mail.com' with the actual email and 'pwd' with the password generated in your Gmail account. To create an app password for your Google account:

    Visit the page (https://myaccount.google.com/apppaswords).

    Select the app and device you want to create a password for. If you don't see the app or device, you can choose "Other (Custom name)

    Click on "Generate". You will see a 16-character password that you can use to sign in to the app or device you selected. Make sure to copy the password as you won't be able to see it again.

    App passwords are only used for apps that don't support two-step verification. If you have enabled two-step verification, you won't need app passwords for most apps.

 

    There are a lot of options and adjustments to this library. You can check them out on Pupy.org and Github.