Unable to send message on behalf of other user in nodejs

Revostat Admin 0 Reputation points
2023-07-25T09:48:38.83+00:00
Hii community,



I am facing difficulty in sending email on behalf of other user, while signing in I am storing user access and refresh tokens and want to send mail in background as server to server communication. 

I am following these steps: 

Fetching user refresh token from db
Getting new access token using ClientSecretCredential.
Using that token to get delegated access token on behalf of that user using OnBehalfOfCredential.
Then using that outcame delegated token to send email on behalf of that user.

`const clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Use the user's refresh token to get a new access token
clientSecretCredential
  .getToken(['https://graph.microsoft.com/.default'], {
    refreshToken: tokens.refresh_token,
  })
  .then((tokenResponse) => {
    const userAccessToken = tokenResponse?.token;
    console.log('User access token:', userAccessToken);

    // Use the user's access token in the OnBehalfOfCredential
    const onBehalfOfCredential = new OnBehalfOfCredential({
      tenantId,
      clientId,
      clientSecret,
      userAssertionToken: userAccessToken,
    });

    // Use the getToken method on the OnBehalfOfCredential to get a delegated access token
    onBehalfOfCredential.getToken(['https://graph.microsoft.com/.default'])
      .then((delegatedTokenResponse) => {
        const delegatedAccessToken = delegatedTokenResponse?.accessToken;
        console.log('Delegated access token:', delegatedAccessToken);

        // Create a Graph API client with the delegated access token
        const graphClient = Client.initWithMiddleware({
          authProvider: {
            getAccessToken: async () => {
              // Return the delegated access token to the Graph API client
              return delegatedAccessToken;
            },
          },
        });

        // Prepare the email payload
        const email = {
          message: {
            subject: 'Test Email',
            body: {
              contentType: 'Text',
              content: 'This is a test email sent via Microsoft Graph API.',
            },
            toRecipients: [
              {
                emailAddress: {
                  address: 'keshav.manuja@reachiq.ai', // Replace with the recipient's email address
                },
              },
            ],
          },
        };

        // Use the Graph API client to send the email on behalf of the user
        graphClient.api('/me/sendMail').post(email)
          .then((response) => {
            console.log('Email sent successfully:', response);
          })
          .catch((error) => {
            console.error('Error sending email:', error);
          });
      })
      .catch((error) => {
        console.error('Error acquiring delegated access token:', error);
      });
  })
  .catch((error) => {
    console.error('Error acquiring user access token:', error);
  });`
Is this flow is correct, I have also tried using MSAL but didn't got any luck. Please help. 
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,037 questions
0 comments No comments
{count} votes