I wrote a simple python code that check how many mails in a mailbox. But if I want it to check two or more mail-accounts at the same time. How can this be done?
Code so far:
from imapclient import IMAPClient
name = 'name_of_account_1'
username = "[email protected]"
password = 'password'
imap_server = "outlook.office365.com"
client = IMAPClient(imap_server, ssl=True)
client.login(username, password)
client.select_folder("INBOX", readonly=True)
result = client.search()
print(f"{name}: {len(result)}")
client.logout()
This output for example:
name_of_account_1: 18
But I would like to check for account_2 and account_3 at the same time :)
CodePudding user response:
Wrap your code in a function:
from imapclient import IMAPClient
def check_mail(args):
name, username, password, imap_server = args
client = IMAPClient(imap_server, ssl=True)
client.login(username, password)
client.select_folder("INBOX", readonly=True)
result = client.search()
client.logout()
return dict(name=name, unread=result)
And then run multiple instances of the function in separate threads:
from multiprocessing.dummy import Pool
NPROC = 6 # max number connections
pool = Pool(NPROC)
tasks = (
("google", "[email protected]", "pass1", "imap.gmail.com"),
("example", "[email protected]", "pass2", "imap.example.com"),
)
results = pool.map(check_mail, tasks)
for result in results:
print(f"{result['name']} had {result['unread']} unread messages")
pool.close()
Note that I've used threads here (multiprocessing.dummy
) rather than processes, as the code is not cpu bound, and that I've factored the check_mail
functions slightly awkwardly to make passing arguments a bit easier.
For more information, check out the multiprocessing docs.