office


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!


Excel / Calc: Convert a Hexadecimal number to Decimal

The following examples allow you to convert hexadecimal values of the format 0xYYYYYY to decimal using a spreadsheet editor like Calc or Excel.

The following codes will remove the first two characters (the value 0x) of the cell B2 and then convert the result to decimal using the HEX2DEC function.

Using the RIGHT function

In this example, we used the RIGHT function with the num_chars parameter to be equal to the number of characters in the cell minus 2. This used to delete the 0x value from the HEX column by removing the first two characters of the cell.
To get the number of characters in the cell we use the LEN function on the cell of interest.

=HEX2DEC(RIGHT(B2,LEN(B2)-2))

Using the SUBSTITUTE function

In the following example we used the SUBSTITUTE function to automatically find the 0x prefix of the HEX value and delete it by replacing it with an empty string.

=HEX2DEC(SUBSTITUTE(B2,"0x",""))

Using the REPLACE function

The last example uses the REPLACE function. Starting from the character in position 1 in the cell, it replaces the sub-string of size 2 with the empty string and thus deleting the prefix. Please note that this function is not zero-based so the first character is at position 1 and not at position 0.

=HEX2DEC(REPLACE(B2,1,2,""))

Functions Legend:

  • RIGHT(text,[num_chars])RIGHT returns the last character or characters in a text string, based on the number of characters you specify in the variable num_chars. RIGHT always counts each character, whether single-byte or double-byte, as 1, no matter what the default language setting is.
  • LEN(text)LEN returns the number of characters in a text string. Again, LEN always counts each character, whether single-byte or double-byte, as 1, no matter what the default language setting is.
  • HEX2DEC(number)HEX2DEC converts a hexadecimal number to decimal.
  • SUBSTITUTE(text, old_text, new_text, [instance_num]) – Substitutes new_text for old_text in a text string. You can use SUBSTITUTE when you want to replace specific text in a text string.
  • REPLACE(old_text, start_num, num_chars, new_text)REPLACE replaces part of a text string, based on the number of characters you specify, with a different text string. Use REPLACE when you want to replace any text that occurs in a specific location in a text string. REPLACE always counts each character, whether single-byte or double-byte, as 1, no matter what the default language setting is.