Hi All,
I have same issue (got 403 forbidden) when access microsoft graph with url:
v1.0/users/<email sender>/sendMail
and this is my msal-node method:
import * as msal from "@azure/msal-node";
//import static config
import {
TENANT_ID,
CLIENT_ID,
CLIENT_SECRET,
AAD_ENDPOINT,
GRAPH_ENDPOINT,
} from "@config/email.config";
//configurasi object untuk dapat melewati proses instanciate MSAL
const msalConfig: { auth: msal.NodeAuthOptions } = {
auth: {
clientId: CLIENT_ID,
authority: AAD_ENDPOINT + "/" + TENANT_ID,
clientSecret: CLIENT_SECRET,
},
};
//interface untuk token request
interface tokenRequestIface {
scopes: string[];
}
//Dalam alur credential klien, izin perlu diberikan di portal oleh administrator penyewa.
//izin dalam hal ini ditentukan oleh scope seperti dibawah
const tokenRequest: tokenRequestIface = {
scopes: [GRAPH_ENDPOINT + "/.default"],
};
//definisikan api graph microsoft endpoint url
const apiConfig: { uri: string } = {
uri: GRAPH_ENDPOINT + "/v1.0/users",
};
//inisiasi sebuah confidential aplikasi client
const cca = new msal.ConfidentialClientApplication(msalConfig);
//buat fungsi untuk mendapatkan token
async function getToken(tokenRequest: tokenRequestIface) {
return await cca.acquireTokenByClientCredential(tokenRequest);
}
export { apiConfig, tokenRequest, getToken };
and then i use getToken above to get bearer token for http request to microsoft graph api:
try {
const tokenInfo = await getToken(tokenRequest);
const mail = {
subject: "Microsoft Graph JavaScript Sample",
//This "from" is optional if you want to send from group email. For this you need to give permissions in that group to send emails from it.
from: {
emailAddress: {
address: "yy@microsoft.com",
},
},
toRecipients: [
{
emailAddress: {
address: "xx@microsoft.com",
},
},
],
body: {
content:
"<h1>MicrosoftGraph JavaScript Sample</h1>This is the email body",
contentType: "html",
},
};
const emailSentResponse = await callAPI({
url: "v1.0/users/yy@microsoft.com/sendMail",
accessToken: tokenInfo?.accessToken,
method: "post",
body: { message: mail, saveToSentItems: false },
});
res.send(emailSentResponse);
} catch (error: any) {
console.log("error send email", error);
const statusCode: number | undefined = error.response?.status;
if (statusCode) {
return res.status(statusCode).send(error);
}
res.status(500).send(error);
}
after finish all code, i hit through postman and get 403 like this:
{
"message": "Request failed with status code 403",
"name": "AxiosError",
"stack": "AxiosError: Request failed with status code 403\n at settle (/Users/fhi-it-dev/Documents/email-SMS-API/node_modules/axios/lib/core/settle.js:19:12)\n at Unzip.handleStreamEnd (/Users/fhi-it-dev/Documents/email-SMS-API/node_modules/axios/lib/adapters/http.js:548:11)\n at Unzip.emit (node:events:525:35)\n at Unzip.emit (node:domain:489:12)\n at endReadableNT (node:internal/streams/readable:1358:12)\n at processTicksAndRejections (node:internal/process/task_queues:83:21)",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"adapter": [
"xhr",
"http"
],
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {
"Blob": null
},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Authorization": "Bearer xxxxxxxxxxxxxx",
"User-Agent": "axios/1.3.3",
"Content-Length": "343",
"Accept-Encoding": "gzip, compress, deflate, br"
},
"baseURL": "https://graph.microsoft.com",
"method": "post",
"data": "{\"message\":{\"subject\":\"Microsoft Graph JavaScript Sample\",\"from\":{\"emailAddress\":{\"address\":\"yyy@fullertonhealth.com\"}},\"toRecipients\":[{\"emailAddress\":{\"address\":\"xxx@fullertonhealth.com\"}}],\"body\":{\"content\":\"<h1>MicrosoftGraph JavaScript Sample</h1>This is the email body\",\"contentType\":\"html\"}},\"saveToSentItems\":false}",
"url": "v1.0/users/yyy@fullertonhealth.com/sendMail"
},
"code": "ERR_BAD_REQUEST",
"status": 403
}
Please help, all setting already ok, (enable email, and also applications permissions like above....