Technology Blog Posts by Members
cancel
Showing results for 
Search instead for 
Did you mean: 

Introduction

Email notifications are an essential part of many enterprise integration scenarios. SAP Cloud Integration (SAP CPI), part of SAP Integration Suite, is frequently used to send automated notifications, monitoring reports, business updates, and integration error alerts.

Traditionally, these scenarios may use SMTP authentication to send emails through Microsoft 365. However, organizations looking to modernize their authentication mechanisms may prefer an API-based approach using Microsoft Graph API and OAuth 2.0.

In this blog, I will demonstrate how to integrate SAP Cloud Integration with Microsoft Graph API to send emails containing HTML-formatted content and file attachments.

The implementation covers:

  • Configuring OAuth 2.0 credentials in SAP Cloud Integration.

  • Preparing email content in HTML format.

  • Encoding file attachments using Base64.

  • Constructing the Microsoft Graph API request payload.

  • Retrieving the access token through a Groovy script.

  • Invoking the Microsoft Graph sendMail endpoint using an HTTP receiver adapter.

This approach can be used for automated notifications, scheduled reports, and other integration scenarios where SAP Cloud Integration needs to send emails through Microsoft 365.

Solution overview

The solution consists of two major components:

  1. Microsoft Entra ID configuration: Establishes the application and authentication configuration required to access Microsoft Graph API.

  2. SAP Cloud Integration configuration: Prepares the email content, retrieves the OAuth access token, and sends the request to Microsoft Graph API.

Prerequisites

Before implementing the solution, ensure that the following prerequisites are met:

  • Access to SAP Integration Suite with permission to create and deploy integration flows.

  • Access to a Microsoft 365 mailbox that will be used to send emails.

  • Appropriate permissions to configure the application and authentication settings in Microsoft Entra ID.

  • The required Microsoft Graph API mail-sending permission and consent.

  • The application details and OAuth configuration values required by SAP Cloud Integration.

The Microsoft Entra ID configuration must be completed before configuring the OAuth credential in SAP Cloud Integration.

Refer to the accompanying Microsoft Graph API configuration guide for the Microsoft-side setup.

Cloud Integration - Send Mail via Microsoft Graph ... - SAP Community

Configure OAuth 2.0 credentials in SAP Cloud Integration



Step 1- configure the credentials: 
1.  Login to system and navigate to "monitor'.

2.  click 'security materials'

3. Create OAuth2 Authorization Code

4.  select Provider: Microsoft 365

5. give it a suitable name.

6.enter authorization and token URL ,client id , client secret received from configuration azure account.

7. enter 'user name ' - the email which will be sending emails and respective password.

8.in the scope , enter this:

openid profile offline_access https://graph.microsoft.com/Mail.Send

oauth_graphapi.png

 

9. click deploy, then click on 3 dots after deployment and  select Authorize.

10.Make sure to follow the step 9 in your VPN system ( if this is customer specific email/Azure account).

This will allow you activate the authorization.

oauth_graphapi1.png

 

Configure the SAP Cloud Integration flow

Create an iflow like below: 

g1.png

 

 

1. configure 'timer' to run the iflow as required.

2. configure the Content Modifier (CM_SetAttachmentbody) here I am storing the csv data in text format in message body of CM.

3. configure 'Base64 Encoder' to convert the attachment in 'base 64' as Graph API process the attachment in this format.
4.  configure CM_HTMLMail, here in the property, store the output from base encoder and in message body store the HTML data( for mail body ).


graph2.png

 

g3.png

 

 

5. CM_Property- create properties like below: these values will be used in graphAPI json body.

use the email ids in BCC separated by ; ( semicolon).
if you need, you can create email or CC email as well instead of bccemail.
g2.png



6. use this groovy to generate the JSONbody to call Graph API. In this groovy emails id which are separated by , or ; will be created separately in JSON to send emails to all ids mentioned.

import com.sap.gateway.ip.core.customdev.util.Message
import groovy.json.JsonOutput

def Message processData(Message message) {

    // Read properties
    String toEmail        = message.getProperty("toEmails") as String
    String ccEmail        = message.getProperty("ccEmails") as String
    String bccEmail       = message.getProperty("bccEmails") as String
    String subject        = message.getProperty("mailsubject") as String
    String htmlBody       = message.getProperty("mailbody") as String
    String attachmentName = message.getProperty("attfilename") as String
    String attachmentData = message.getProperty("attachmentfile") as String

    // Convert email list to Microsoft Graph recipient format
    def createRecipients = { String emailString ->

        if (!emailString?.trim()) {
            return []
        }

        emailString
            .split(/[;,]/)
            .collect { it.trim() }
            .findAll { it }
            .unique()
            .collect { email ->
                [
                    emailAddress: [
                        address: email
                    ]
                ]
            }
    }

    // Create recipients
    def toRecipients = createRecipients(toEmail)
    def ccRecipients = createRecipients(ccEmail)
    def bccRecipients = createRecipients(bccEmail)
    // Make sure HTML body is treated as HTML
    if (!htmlBody?.trim()) {
        htmlBody = ""
    }

    // Build Microsoft Graph request
    def graphRequest = [
        message: [
            subject: subject ?: "",
            body: [
                contentType: "HTML",
                content: htmlBody
            ],
            toRecipients: toRecipients,
            ccRecipients: ccRecipients,
            bccRecipients : bccRecipients 
        ],
        saveToSentItems: false
    ]

    // Add attachment if available
    if (attachmentName?.trim() && attachmentData?.trim()) {

        graphRequest.message.attachments = [
            [
                "@odata.type": "#microsoft.graph.fileAttachment",
                name: attachmentName,
                contentType: "text/plain",
                contentBytes: attachmentData
            ]
        ]
    } 

    // Convert to JSON
    String jsonBody = JsonOutput.toJson(graphRequest)

    // Set JSON as message body
    message.setBody(jsonBody)

    return message
}

7. use this groovy to fetch the oauth code configured in Step1.

import com.sap.gateway.ip.core.customdev.util.Message
import com.sap.it.api.securestore.SecureStoreService
import com.sap.it.api.securestore.AccessTokenAndUser
import com.sap.it.api.ITApiFactory

def Message processData(Message message) {

    def properties = message.getProperties();


    SecureStoreService secureStoreService =
            ITApiFactory.getService(SecureStoreService.class, null);

    String oauth2AuthorizationCodeCred =
            properties.get("OAUTH2_AUTHORIZATION_CODE_CRED");

    if (oauth2AuthorizationCodeCred == null ||
            oauth2AuthorizationCodeCred.trim().isEmpty()) {

        throw new IllegalStateException(
                "Property OAUTH2_AUTHORIZATION_CODE_CRED is not specified"
        )
    }

    AccessTokenAndUser accessTokenAndUser =
            secureStoreService.getAccesTokenForOauth2AuthorizationCodeCredential(
                    oauth2AuthorizationCodeCred
            )

    String token = accessTokenAndUser.getAccessToken();

   
    message.setHeader("Authorization", "Bearer " + token) ;
    message.setHeader("Content-Type", "application/json") ;
    return message;
}

( both Groovy can be used in any sequence).

8. use request reply with Http sender to configure GraphAPI as given below and Headers as well:
URL- https://graph.microsoft.com/v1.0/me/sendMail
graph7.png

 

8. CM_delete_auth, configure to delete the auth header.

graph8.png

 

9.deploy the iflow, you should get the email  as per HTML and attachment you configured.

graph9.png

 

Troubleshooting

During implementation, validate the following areas if the request fails:

  • HTTP 400 – Bad Request: Check the JSON syntax, recipient arrays, attachment fields, and HTML content escaping.

  • HTTP 401 – Unauthorized: Verify the access token, token audience, expiry, and authentication configuration.

  • HTTP 403 – Forbidden: Check the required Microsoft Graph permissions, consent, and mailbox access.

  • Missing or corrupted attachment: Verify the Base64-encoded content, filename, and content type.

Use the error response from Microsoft Graph API and SAP Cloud Integration message monitoring to identify the actual cause before making configuration changes.

 

Conclusion

This implementation demonstrates how SAP Cloud Integration can use Microsoft Graph API to send HTML-formatted emails with file attachments through Microsoft 365.

By separating authentication configuration, email preparation, and API invocation into distinct steps, the integration flow becomes easier to understand, maintain, and troubleshoot.

The same approach can be extended to scheduled operational reports, integration monitoring notifications, and other enterprise email automation scenarios.

I hope this walkthrough helps SAP Integration Suite developers implement and understand Microsoft Graph API-based email notifications.

Feedback and suggestions for improvement are welcome.

Regards,
Pooja Tiwari

Labels in this area