Always I am getting 401 error when I want to send mail through graph API, while it is generating token successfully

Palash Samanta 0 Reputation points
2025-10-07T16:35:42.8233333+00:00

This is my node js code as below

import axios from 'axios';
import { ConfidentialClientApplication, LogLevel } from '@azure/msal-node';

// Static configuration per your request
const clientId = '****';
const clientSecret = '*******';
const tenantId = process.env.AZURE_TENANT_ID || '*******';
const senderUpn = '******@gmail.com';
const toAddress = '******@gmail.com';

const cca = new ConfidentialClientApplication({
    auth: {
        clientId,
        clientSecret,
        authority: `https://login.microsoftonline.com/${tenantId}`,
    },
    system: {
        loggerOptions: {
            loggerCallback: () => {},
            logLevel: LogLevel.Error,
            piiLoggingEnabled: false,
        },
    },
});

async function acquireAppToken() {
    const scopes = ['https://graph.microsoft.com/.default'];
    const result = await cca.acquireTokenByClientCredential({ scopes });
    return result.accessToken;
}

function buildMessage() {
    return {
        message: {
            subject: 'First Mail From Postman',
            body: {
                contentType: 'Text',
                content: 'The new cafeteria is open.',
            },
            toRecipients: [
                { emailAddress: { address: toAddress } },
            ],
            ccRecipients: [
                { emailAddress: { address: toAddress } },
            ],
        },
        saveToSentItems: true,
    };
}

async function sendMailOnce() {
    try {
        const token = await acquireAppToken();
        console.log('Access token (app-only JWT):', token);
        const url = `https://graph.microsoft.com/v1.0/users/${encodeURIComponent(senderUpn)}/sendMail`;
        const payload = buildMessage();
        const res = await axios.post(url, payload, {
            headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
            validateStatus: () => true,
        });
        if (res.status === 202) {
            console.log('Mail accepted for delivery.');
        } else {
            console.error('Failed to send mail:', res.status, res.statusText, res.data);
            process.exitCode = 1;
        }
    } catch (e) {
        console.error('Error acquiring token or sending mail:', e);
        process.exit(1);
    }
}

sendMailOnce();



When I am running the page its response is coming as like below

Access token (app-only JWT): ********

Failed to send mail: 401 Unauthorized

Always I am getting 401 unauthorized error

I have the app permission as like below

User's image

Requesting the communities help for identification of issue and resolution

Microsoft 365 and Office | Development | Office JavaScript API
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Vergil-V 6,060 Reputation points Microsoft External Staff Moderator
    2025-10-08T00:53:25.2033333+00:00

    Hi @Palash Samanta 
    Thank you for reaching out to the Microsoft Q&A forum!   
    I understand you're encountering a 401 error when running your script using the Microsoft Graph API Send Mail endpoint 
    Based on the code you shared, I noticed that the sender's email address uses a @gmail.com domain, which is not supported by Microsoft Graph. Microsoft Graph is designed to work only with Microsoft 365 services. This means the User Principal Name (UPN) of the sender must belong to a domain that has been added to your Microsoft 365 tenant and must have an active mailbox license. 

    Reference: 

    If you intend to send emails from a @gmail.com address, I recommend using the Gmail API, which is the appropriate endpoint for that service. You can find more details in the official documentation here: https://developers.google.com/gmail/api/guides/sending 

    Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.   

    I sincerely hope this information partially clarifies your situation and assists you in planning your solution. Please do not hesitate to reply if you have any updates.  

    Thank you for your understanding.  


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread. 


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.