How to Implement Continuous Email Monitoring in a Python + O365

54 Views Asked by At

I managed to create a Python + O365 app that logs into my email and prints the emails in the console. Here's the code:

import O365

from O365 import Connection, FileSystemTokenBackend

from O365.account import Account

tokenstorage = FileSystemTokenBackend(token_path='XXX', token_filename='XXX')

scopes_graph  = ['User.Read', 'Mail.ReadWrite', 'Mail.Read', 'OFFLINE_ACCESS']
credentials = ('XXX', 'XXX')

account = Account(credentials, tenant_id='XXX', scopes=scopes_graph, token_backend=tokenstorage)

if not account.is_authenticated:
    account.authenticate()

mailbox = account.mailbox()

inbox = mailbox.inbox_folder()
query = mailbox.new_query()

query = query.on_attribute('Subject').contains('Test')

for message in inbox.get_messages(limit=10, query=query):
    print(message._Message__created, message.sender, message)

The thing is, I would prefer the program to run continuously - perhaps through some kind of an infinite loop. It would be best if it could "wait and listen" for emails so that whenever I receive a new email, it prints a new line in the console 24/7. Do you guys think this is doable? How?

0

There are 0 best solutions below