I have an Office 365 extension that provides its own "Send" button which does some custom processing of the "draft" email and sends it through other means (ie not Office 365 Web). Since the email isn't sent by Outlook it never makes it to the sent folder (which makes sense). I would like to take that draft email and move it to the sent folder and remove the draft flag so it looks like it was sent by Outlook 365 Web.
var getMessageUrl = Office.context.mailbox.restUrl + '/v2.0/me/messages/' + itemId;
var data = JSON.stringify({ 'ToRecipients': [{ 'EmailAddress': { 'Address': 'sheprts#cox.net', 'Name': 'Katie Jordan' } }], 'IsRead': true, 'IsDraft': false });
$.ajax({
url: getMessageUrl,
type: 'PATCH',
dataType: 'json',
headers: { 'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'application/json' },
data: data
})
})
.done(function (item) {
})
.fail(function (error) {
var err = ""
});
The request above works fine except the changing of the draft flag. If this isn't the solution what else can I do? I need to get a draft email into the sent folder as "Not" a draft.
Unfortunately you cannot create non-draft messages using the API.
Change your "other means" and set the "SaveInSentFolder" flag; or change to SMTP for your "other means".
Related
Issue
I have a MediaRecorder video of up to 400 KB that I need to send to the server.
I want to be able to also send the video when someone exits the page.
My code looks kind of like this:
window.onpagehide = (e) => {
e.preventDefault();
var blob = new Blob(this.data, {type: "video/mp4"});
var file = new File([blob], "recording");
var formData = new FormData();
formData.append("recording", file);
axios.post('my-site-url', formData)
.then(function (response) {
if(response.data.result) {
console.log("email has been sent")
} else {
console.log("failed to send email")
}
})
.catch(({response}) => {
console.log("an error occured during email call");
console.error(response);
})
return null;
}
However window.onpagehide doesn't allow async functions so axios.post isn't running at all.
NB: this issue is tested only on IOS Safari.
For Chrome and Edge I am using onbeforeunload and it works fine
Question
What synchronous axios.post alternative can I use for this scenario?
What I tried
navigator.sendBeacon
It looked pretty promising, but it has a limit of 64KB, so I couldn't rely on it.
fetch
fetch('my-site-url', {
method: 'POST',
body: formData
});
error message:
Fetch API cannot load my-site-url due to access control checks.
ajax
$.ajax({
type: 'POST',
async: false,
url: "my-site-url",
data: formData,
processData: false,
timeout: 5000,
});
error message:
XMLHttpRequest cannot load my-site-url due to access control checks.
XMLHttpRequest
var request = new XMLHttpRequest();
request.open('POST', 'my-site-url', false);
request.send(formData);
if (request.status === 200) {
console.log("success!");
}
error message:
XMLHttpRequest cannot load my-site-url due to access control checks.
But these are not CORS related issues, as they only happen when inside onpagehide on Safari.
Is there a way to send email from Twilio function? I understand that we can use sendgrid. I am looking a simpler solution.
Twilio evangelist here. 👋
As of now, you can use SendGrid from within a Twilio Function. The code below does the job for me and I just sent an email via a function
exports.handler = function(context, event, callback) {
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'sjudis#twilio.com',
from: 'test#example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg)
.then(() => {
callback(null, 'Email sent...');
})
.catch((e) => {
console.log(e);
})
};
The above email will most like end up in spam as test#example.com is not a very trust worthy email address. If you want to send emails from your own domains additional configuration is needed.
To run the code inside of the function, you have to make sure to install the sendgrid/mail mail dependency and provide the sendgrid token in the function configuration.
If you want to use this function to power e.g. messages you have to make sure that your return valid TwiML. :) When you create a new function you will get examples showing on how to do that.
Hope that helps. :)
Another way is to use the SendGrid API
const got = require('got');
exports.handler = function(context, event, callback) {
const requestBody = {
personalizations: [{ to: [{ email: context.TO_EMAIL_ADDRESS }] }],
from: { email: context.FROM_EMAIL_ADDRESS },
subject: `New SMS message from: ${event.From}`,
content: [
{
type: 'text/plain',
value: event.Body
}
]
};
got.post('https://api.sendgrid.com/v3/mail/send', {
headers: {
Authorization: `Bearer ${context.SENDGRID_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
})
.then(response => {
let twiml = new Twilio.twiml.MessagingResponse();
callback(null, twiml);
})
.catch(err => {
callback(err);
});
};
};
Source: https://www.twilio.com/blog/2017/07/forward-incoming-sms-messages-to-email-with-node-js-sendgrid-and-twilio-functions.html
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.
So we are using Firebase to send notifications to our users on our iOS app. It works great in the console, but now we are looking to allow a few more people to send notifications, and we don't really want them signing into Firebase to do that. One solution we came up with is to put a form on our website and let them sign in and send notifications from there, but we can't get it to work. The code below is a stripped down version of what we have right now. It uses the cloud messaging API to send an HTTP POST request to a specific topic and Firebase responds with a message_id, however no message is delivered on any of the devices.
<!DOCTYPE html>
<html>
<body>
<input id="title"></input>
<input id="message"></input>
<button>Submit</button>
</body>
<script src="https://code.jquery.com/jquery-1.12.2.min.js" integrity="sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=" crossorigin="anonymous"></script>
<script>
$("button").click(function () {
var title = $("#title").val();
var message = $("#message").val();
var param = {
"to" : "/topics/myTopic",
"content_available" : true,
"notification" : {
"title" : title,
"body" : message
}
};
$.ajax({
url: 'https://fcm.googleapis.com/fcm/send',
type: "POST",
headers: { 'Authorization': 'key=<myKey>', 'Content-Type': 'application/json' },
data: JSON.stringify(param),
success: function () {
alert("success");
},
error: function(error) {
alert("error: "+error);
}
});
});
</script>
</html>
Solution:
After we played around with it a bit more, we found that content_available should really be false in order to actually display a notification in our app. We also made sure to implement jQuery variables correctly. You can see our improved script for handling everything below.
$("button").click(function () {
// Grab the input values
$title = $("#title").val();
$message = $("#message").val();
// Verify that the message is not left empty
if ( $message.length < 2 ){
// Message is empty
return;
}
// Create the JSON object
var paramaters = {
"to" : "/topics/test",
"content_available" : false,
"notification" : {
"title" : $title,
"body" : $message
}
};
// Send request
$.ajax({
url: 'https://fcm.googleapis.com/fcm/send',
type: "POST",
headers: { 'Authorization': 'key=$key', 'Content-Type': 'application/json' },
data: JSON.stringify(paramaters),
success: function (e) {
// Process succeeded
console.log(e);
},
error: function(error) {
// Display error message
}
});
});
We also made sure that our server keys were not included directly in our code as Frank mentioned in his comment. Everything now works and we are successfully receiving notifications.
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()