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:
- Access to the Office 365 admin portal
- Basic knowledge of Python programming
- 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:
- Log into the Office 365 admin portal at https://admin.microsoft.com.
- Locate and click on the link to Azure Active Directory.
- 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:
- Navigate to the API permissions page within the Azure Active Directory.
- 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:
- Go to the Enterprise applications page in Azure Active Directory.
- Select your app.
- 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@domain.com')
)
config = Configuration(server='outlook.office365.com', credentials=creds, auth_type=OAUTH2)
a = Account(
primary_smtp_address='email@domain.com',
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:
- The
exchangelib
library is imported, and logging is set up to display any errors. - OAuth2 credentials are created using the previously obtained client ID, client secret, tenant ID, and primary SMTP address.
- A configuration object is created with the server address, credentials, and authentication type.
- An
Account
object is initialized using the email address, disabling autodiscover, and providing the configuration. - The code retrieves the two most recent inbox messages and prints their subjects.
- 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!