Search code examples
pythonmultithreadingexchange-serverexchangewebservicesexchangelib

Exchangelib with multithreading python3


I am trying to delete recoverable items in @OUTLOOK/@HOTMAIL many mails very fast

I was trying multithreading, but exactly the process of connecting to an mail account and deleting mails going in single thread, as I understand due to logs time

from exchangelib import DELEGATE, Account, Credentials
import threading

def main(login,password):
                    print('started',time.time())
                    credentials = Credentials(
                        username=login,  # Or [email protected] for O365
                        password=password
                    )
                    a = Account(
                        primary_smtp_address=login, 
                        credentials=credentials, 
                        autodiscover=True, 
                        access_type=DELEGATE
                    )
                    
                    a.protocol.TIMEOUT=15
                    
                    ###Tried adding this, but no results
                    #a.protocol.SESSION_POOLSIZE=50
                    #a.protocol.CONNECTIONS_PER_SESSION=50

                    a.recoverable_items_deletions.empty()
                        
                    a.protocol.close()
                    print('done',time.time())
for i in logins_passwords_dict:
    threading.Thread(target=main, args=(i[0],i[1],))

the code works, but in single thread (time value is just for an example)

started 17000
started 17000
started 17000
done 17010
done 17020
done 17030

I am looking to speed up the process of deleting recoverable items


Solution

  • Check out the max_connections option: https://ecederstrand.github.io/exchangelib/#optimizing-connections

    That will allow exchangelib to create a larger connection pool. If you use that approach, then you should only create one Account object and pass that to your main() method.

    However, .empty() sends a single command to the server to delete the folder. The server does the actual work of emptying the folder. It will not help to run the command in parallel.

    Finally, it's possible that you are not allowed to empty the recoverable items folder. Many servers have policies set up to prevent this, due to required archiving.