Email sent but not received when using MSGraph API - microsoft-graph-api

When I Hit ms graph API with my Nodejs code to send the email, an email is sent with no error displayed but the email is received in the outlook sent email which I'm using
I have proper accessToken what happing behind this please help here
Code below
const sendNotification = async (from, message) => {
const access_token = await getAuthToken();
try {
const response = await axios({
url: `${GRAPH_ENDPOINT}/v1.0/users/${from}/sendMail`,
method: "POST",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
data: JSON.stringify(message),
});
console.log("sendNotification status", response.statusText);
} catch (error) {
console.log(error);
}
};

Related

Error 504 - Using Twilio Functions to Send Alerts to Slack

I'm using Twilio Functions as a webhook to send Slack messages anytime an error occurs. The error message is successfully sent to Slack. However, this triggers Error code 504 (runtime application timed out) in Twilio. From the Twilio documentation, it seems I'm not properly implementing the callback method. Is there something I'm missing?
const https = require("https");
// Make sure to declare SLACK_WEBHOOK_PATH in your Environment
// variables at
// https://www.twilio.com/console/runtime/functions/configure
exports.handler = function(context, event, callback) {
const { AccountSid } = event;
const message = `New error for Twilio Account ${AccountSid}.`
const slackBody = JSON.stringify({
channel: "#channel",
icon_emoji: ":test_tube:",
username: "Twilio Alert",
attachments: [{
fallback: "twilio alert",
color: "#d00000",
pretext: "",
text: message
}]
});
// Form our request specification
const options = {
host: "hooks.slack.com",
port: 443,
path: context.SLACK_WEBHOOK_PATH,
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": slackBody.length
}
};
// send the request
const post = https.request(options, res => {
// only respond once we're done, or Twilio's functions
// may kill our execution before we finish.
res.on("end", () => {
// respond with an empty message
return callback(null);
});
});
post.on('error', (e) => {
console.log(e);
});
post.write(slackBody);
post.end();
}

Post request returning 403 when trying to call IBM AppID management API /users

I'm trying to create a custom IBM AppID Management Api interface in my application.
In order to do that, I'm using IBM IAM Token Manager library to get an IAM access token.
const itm = require('#ibm-functions/iam-token-manager')
const m = new itm({
"iamApiKey": apiKey
})
m.getAuthHeader().then(token => {
console.log("this one won't work", token)
}
var headers =
{
'accept': 'application/json',
'Authorization': token,
'Content-Type': 'application/json'
};
var options =
{
url: replacedIssUrl+"/users",
method: 'POST',
headers: headers,
body: dataString
};
function callback(error, response, body) {
console.log(response)
if (!error && response.statusCode == 200) {
console.log(body); //returns "body: "Forbidden"
}
}
request(options, callback)
Whenever I try to pre-register a user with the library's generated token, the callback returns Status 403 - Forbidden, but if it gets the IAM Access token directly through ibmcloud shell (ibmcloud iam oauth-tokens), it works fine.
Does anybody have any clue why this is happening? I know for a fact that the IAM Token Manager library generated access token is working, because I'm using it to get the user ID on the same code.
When something is wrong with my Access Token, it usually returns "Unauthorized", not "Forbidden".
I have no clue why this is happening.
Thanks in advance.
When passing an IAM token in the headers, App ID expects it to be preceded by the "Bearer " string :
var headers =
{
'accept': 'application/json',
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
};

Microsoft Graph sendMail doesn't work and returns NULL

I'm trying to send e-mails with MS Graph 1.0 and I have not any get any result or response. E-Mails haven't been sent and sendMail method don't return any error o message... it only says "null".
My code is based on this example https://github.com/microsoftgraph/msgraph-sdk-javascript#post-and-patch and looks like this:
// Initialize Graph client
const client = graph.Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
try {
// construct the email object
var mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [{
emailAddress: {
address: "mail#domain.com"
}
}],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html"
}
};
client
.api('/me/sendMail')
.post({message: mail}, (err, res) => {
console.log("---> " + res);
});
console.log("Try ends");
} catch (err) {
parms.message = 'Error retrieving messages';
parms.error = { status: `${err.code}: ${err.message}` };
parms.debug = JSON.stringify(err.body, null, 2);
res.render('error', parms);
}
I guess mail var needs a header, but anyway, API should return me something, right? And, obviously, which is the problem with the email sending?
I finally added rawResponse to .post call and look at err log...
client
.api('/me/sendMail')
.header("Content-type", "application/json")
.post({message: mail}, (err, res, rawResponse) => {
console.log(rawResponse);
console.log(err);
});
... and I could see that I had problem with my authentication token. So, I was using the api correctly and code from the question is ok.

HTTP request cannot get the contact photo using Microsoft Graph API

If I use the library #microsoft/microsoft-graph-client, I can get the contact photo as binary data, convert it to base64 and get the correct photo with the code below:
const request = require('request')
const microsoftGraph = require('#microsoft/microsoft-graph-client');
let token = token-value
let client = getMicrosoftGrapClient(token);
let id = contact-id;
let url = '/me/contacts/' + id + '/photo/$value';
client.api(url).get().then((res) => {
//console.log(res);
var encodedImage = new Buffer(res, 'binary').toString('base64');
console.log("encodedImage>>>>>>>>>>>>>>>>>>>>>>")
console.log (encodedImage);
}).catch((err) => {
console.log(err);
});;
function getMicrosoftGrapClient (token) {
// Create a Graph client
return microsoftGraph.Client.init({
authProvider: (done) => {
// Just return the token
done(null, token);
}});
}
I cannot get the correct contact photo with the HTTP GET. The HTTP
response code is 200 but the body is not the binary data of photo.
Please let me know what the error is. Here is the code:
const request = require('request')
request({
url: "https://graph.microsoft.com/v1.0/me/contacts/{contact_id}/photo/$value",
method: 'GET',
headers: {
'content-type': 'image/jpg',
'Authorization': 'Bearer {token}'
}
}, function (error, response, body){
console.log(error);
var encodedImage = new Buffer(body, 'binary').toString('base64');
console.log(encodedImage);
});
Encoding needs to be explicitly specified as
encoding: null
In that case the body will be of type Buffer, instead of the default (string).
And content-type could be omitted.
Example
request({
url: "https://graph.microsoft.com/v1.0/me/photo/$value",
method: 'GET',
encoding: null,
headers: {
'Authorization': 'Bearer ' + accessToken,
}
}, function (error, response, body) {
var encImage = new Buffer(body, 'binary');
fs.writeFileSync(filePath, encImage );
});

Fetch in ReactNative can not deliver the paras in body to the server

ReactNative provide me with fetch to send a httpRequest.The attribute of body includes my parameters which are to send to the server.But I can't get the parameters on my server.My codes are here:
fetch(`${keys.api}/login`,
{
method: 'POST',
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}
).then((response) => {
if(response._bodyText == 'success') {
this.props.resetToRoute({
name: '主页',
component: Main,
hideNavigationBar: true,
});
} else {
this.cancelLogin();
}
}).catch((error) => {
console.warn(error);
this.cancelLogin();
});
And the console in my J2EE Web Server prints the message:
The httpRequest message
There is no parameter in my httpRequest(In other words,The body can not deliver any parameters),I need help.
It's dangerous to show my username and password in the url.
i have met the problem twice on jetty-8.1 on different condition
first ,you should know that it has nothing to do with react-native
fetch put the data in body to header "payload" when the client made a request.i thought jetty-8.1 does not support get data from the payload header
,change the way
Getting request payload from POST request in Java servlet will be helpful
or maybe use the websockt or XMLhttpRequest object to send a request
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString()

Resources