Python: How to Connect and Use Office 365 Email


As Office 365 transitions away from Basic authentication and embraces Multi-Factor Authentication (MFA) for end-users and OAuth for other purposes, connecting Python to Office 365 email requires a slightly different approach. This blog post will explore how to connect Python to Office 365 email using the exchangelib library and OAuth2 credentials. By following these steps, you can access and interact with your Office 365 email programmatically.

Prerequisites: Before diving into the code, ensure you have the following prerequisites in place:

  1. Access to the Office 365 admin portal
  2. Basic knowledge of Python programming
  3. Required Python libraries: exchangelib

Step 1: Registering an App and Gathering Credentials: To connect Python with Office 365 email, you must register an application in the Azure Active Directory. Here’s how you can do it:

  1. Log into the Office 365 admin portal at https://admin.microsoft.com.
  2. Locate and click on the link to Azure Active Directory.
  3. Register a new app and make a note of the Directory (tenant) ID, Application (client) ID, and the secret (client secret).

Step 2: Granting App Permissions: To grant necessary permissions to the registered app, follow these steps:

  1. Navigate to the API permissions page within the Azure Active Directory.
  2. Add the full_access_as_app permission for your app.

Step 3: Verify App Permissions: To ensure the app has the required permissions, perform the following steps:

  1. Go to the Enterprise applications page in Azure Active Directory.
  2. Select your app.
  3. Continue to the Permissions page and verify that your app has the full_access_as_app permission.

Connecting Python to Office 365 Email: Now that we have the required credentials and permissions in place, let’s connect Python to Office 365 email using the exchangelib library. Here’s the code snippet to establish the connection:

import logging
from exchangelib import Account, Configuration, Identity, OAUTH2, OAuth2Credentials

logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start...')

creds = OAuth2Credentials(
    client_id='4e89**********************',
    client_secret='cx67**********************',
    tenant_id='gt6**********************',
    identity=Identity(primary_smtp_address=r'[email protected]')
)

config = Configuration(server='outlook.office365.com', credentials=creds, auth_type=OAUTH2)

a = Account(
    primary_smtp_address='[email protected]',
    autodiscover=False,
    config=config
)

# Print first inbox messages in reverse order
for item in a.inbox.all().only('subject').order_by('-datetime_received')[:2]:
    print(item.subject)

a.protocol.close()

logging.debug('End...')

Make sure to replace the code’s placeholders with your credentials and email address.

Explanation of the Code:

  1. The exchangelib library is imported, and logging is set up to display any errors.
  2. OAuth2 credentials are created using the previously obtained client ID, client secret, tenant ID, and primary SMTP address.
  3. A configuration object is created with the server address, credentials, and authentication type.
  4. An Account object is initialized using the email address, disabling autodiscover, and providing the configuration.
  5. The code retrieves the two most recent inbox messages and prints their subjects.
  6. The connection is closed, and the logging is finalized.

Conclusion: By following the steps outlined in this blog post, you can easily connect Python to your Office 365 email using the exchangelib library and OAuth2 credentials. This enables you to automate email-related tasks, retrieve messages, send emails, and perform various other operations programmatically. Embracing OAuth2 and MFA adds an extra layer of security to your email communication. Enjoy leveraging the power of Python and Office 365 to streamline your workflows!

This post is also available in: Greek

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.