My starting point is this answer about forwarding incoming SMS messages to email with node.js, sendgrid and Twilio Functions: https://stackoverflow.com/a/50728459/
I also looked at this tutorial: https://support.twilio.com/hc/en-us/articles/223134287-Forwarding-SMS-messages-to-another-phone-number
Can I combine both actions in one Twilio function? I prefer to combine them into one function because I don't see a method to configure a Twilio number to perform two separate "Messaging actions" in response to a message coming in. I can only pick one function to run.
I hope I simply need to add a few lines of code to the answer given above:
let twiml = new Twilio.twiml.MessagingResponse();
twiml.message(`${event.From}: ${event.Body}`, {
to: '+13105555555'
});
callback(null, twiml);
In the function, I would like to forward the SMS to another phone number first, then forward the message to email.
The Twilio function environment variables are set up.
Here's my code:
const https = require('https');
exports.handler = function (context, event, callback) {
let sms_twiml = new Twilio.sms_twiml.MessagingResponse();
sms_twiml.message(`${event.From}: ${event.Body}`, {
to: context.TO_SMS_NUMBER
});
//executing a callback terminates the function
//callback(null, sms_twiml);
let postData = JSON.stringify({
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
}]
});
let postOptions = {
host: 'api.sendgrid.com',
port: '443',
path: '/v3/mail/send',
method: 'POST',
headers: {
'Authorization': 'Bearer ${context.SENDGRID_API_KEY}',
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
}
};
let req = https.request(postOptions, function (res) {
let email_twiml = new Twilio.email_twiml.MessagingResponse();
callback(null, email_twiml);
});
req.write(postData);
req.end();
};
I'm getting ERROR - 11200
HTTP retrieval failure There was a failure attempting to retrieve the contents of this URL. An 11200 error is an indicator of a connection failure between Twilio and your service.