Module microsoft.outlook.mail

ballerinax/microsoft.outlook.mail Ballerina library

3.0.0

Overview

Microsoft Outlook Mail is a widely used email service from Microsoft, available as part of the Microsoft 365 suite.

The ballerinax/microsoft.outlook.mail connector offers APIs to connect and interact with the Microsoft Outlook Mail API endpoints, specifically based on the Microsoft Graph REST API v1.0. It supports sending, receiving, and managing email messages, creating and organizing mail folders, managing file and item attachments, drafting and deleting messages, and reading or updating message properties such as subject, body, flags, and categories.

Setup guide

To use the Microsoft Outlook Mail connector, you need a Microsoft account and an application registered in Azure Active Directory (Azure AD) with the appropriate OAuth2 credentials.

Step 1: Sign in to Azure Portal

  1. If you don't have a Microsoft Azure account, you can create one for free at https://azure.microsoft.com.

  2. Go to the Azure Portal and sign in with your Microsoft account. From the home page, navigate to Entra.

    Azure Portal

Step 2: Register an application

  1. In the Microsoft Entra admin center, navigate to App registrations from the left sidebar.

    Entra main page

  2. Click New registration in the top menu.

  3. Fill in the application details.

    • Name: Provide a name for your app (e.g., Ballerina Outlook Connector App)
    • Supported account types: Select Any Entra ID Tenant + Personal Microsoft Accounts.
    • Redirect URI: Select Web and enter your redirect URI (e.g., http://localhost for local testing).

    Register application

  4. Click Register.

Step 3: Add API permissions

  1. In your registered application, navigate to API permissions from the left sidebar.

  2. Click Add a permission > Microsoft Graph > Delegated permissions.

    Add API permissions

  3. Add the following permissions.

    • Mail.Read
    • Mail.ReadWrite
    • Mail.Send
    • MailboxSettings.Read
    • MailboxSettings.ReadWrite
    • offline_access
  4. Click Add permissions.

  5. When prompted to grant consent, click Accept to allow the app access to the requested permissions.

    Allow permission

Step 4: Get the client ID and client secret

  1. Navigate to Overview in your registered application. Copy the Application (client) ID and save it as your clientId.

  2. Navigate to Certificates & secrets > Client secrets > New client secret.

    Add client secret

  3. Provide a description, choose an expiry duration, and click Add.

  4. Copy the generated Value of the secret and save it as your clientSecret.

Step 5: Set up the authentication flow

Before using the connector, obtain a refresh token using the following OAuth2 authorization code flow:

  1. Construct an authorization URL using the format below. Replace <CLIENT_ID>, <REDIRECT_URI> and <SCOPE> with your specific values:

    Copy
    https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=<CLIENT_ID>&response_type=code&redirect_uri=<REDIRECT_URI>&scope=<SCOPE>&response_mode=query

    Example values for <SCOPE>: Mail.Read Mail.ReadWrite Mail.Send User.Read offline_access

  2. Open the URL in a browser and sign in with your Microsoft account. Grant the requested permissions.

  3. After authorization, you will be redirected to your redirect URI with a code parameter in the URL. Copy this code.

  4. Exchange the authorization code for tokens by running the following curl command. Replace the placeholder values with your specific values. For SCOPE you can use this Mail.Read Mail.ReadWrite Mail.Send User.Read offline_access.

    Copy
    curl --location 'https://login.microsoftonline.com/common/oauth2/v2.0/token' \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --data-urlencode 'grant_type=authorization_code' \
    --data-urlencode 'code=<CODE>' \
    --data-urlencode 'redirect_uri=<REDIRECT_URI>' \
    --data-urlencode 'client_id=<CLIENT_ID>' \
    --data-urlencode 'client_secret=<CLIENT_SECRET>' \
    --data-urlencode 'scope=<SCOPE>'

    The response will contain your access token and refresh token.

    Copy
    {
        "token_type": "Bearer",
        "scope": "<SCOPE>",
        "refresh_token": "<REFRESH_TOKEN>",
        "access_token": "<ACCESS_TOKEN>",
        "expires_in": 3600
    }
  5. Store the refresh_token securely for use in your application.

  6. Use https://login.microsoftonline.com/common/oauth2/v2.0/token as the REFRESH_URL.

Quickstart

To use the microsoft.outlook.mail connector in your Ballerina application, update your .bal file as follows:

Step 1: Import the module

Import the microsoft.outlook.mail module.

Copy
import ballerinax/microsoft.outlook.mail;

Step 2: Instantiate a new connector

  1. Create a Config.toml file and configure the credentials obtained above:
Copy
clientId = "<CLIENT_ID>"
clientSecret = "<CLIENT_SECRET>"
refreshToken = "<REFRESH_TOKEN>"
refreshUrl = "<REFRESH_URL>"
  1. Instantiate a mail:ConnectionConfig with the obtained credentials and initialize the connector with it.
Copy
configurable string clientId = ?;
configurable string clientSecret = ?;
configurable string refreshToken = ?;
configurable string refreshUrl = ?;

final mail:Client outlookClient = check new ({
   auth: {
      clientId,
      clientSecret,
      refreshToken,
      refreshUrl
   }
});

Step 3: Invoke the connector operation

Now, utilize the available connector operations. A sample use case is shown below.

Copy
// List the most recent messages in the mailbox
public function main() returns error? {
   mail:MicrosoftGraphMessageCollectionResponse response = check outlookClient->listMessages(
      dollarTop = 5,
      dollarSelect = ["id", "subject", "from", "receivedDateTime", "isRead"]
   );
   mail:MicrosoftGraphMessage[] messages = response.value ?: [];
   foreach mail:MicrosoftGraphMessage message in messages {
      io:println("Subject: ", message?.subject, " | Read: ", message?.isRead);
   }
}

Examples

The microsoft.outlook.mail connector provides practical examples illustrating usage in various scenarios. Explore these examples, covering the following use cases.

  1. Automated email notifications: Automates weekly project status report distribution. Creates a dedicated mail folder, drafts an HTML-formatted report email with an attachment, sends the draft, and lists recent sent messages to confirm delivery.

  2. Email inbox management: Implements a customer support inbox triage workflow. Lists unread messages, fetches message details, marks messages as read after review, creates an organized folder for processed tickets, and deletes spam or resolved messages.

Import

import ballerinax/microsoft.outlook.mail;Copy

Other versions

See more...

Metadata

Released date: about 5 hours ago

Version: 3.0.0

License: Apache-2.0


Compatibility

Platform: any

Ballerina version: 2201.12.0

GraalVM compatible: Yes


Pull count

Total: 1783

Current verison: 0


Weekly downloads


Source repository


Keywords

Communication/Email

Cost/Paid

Vendor/Microsoft

Area/Communication

Type/Connector


Contributors