Skip to content

Instantly share code, notes, and snippets.

@Gipetto
Last active June 17, 2020 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gipetto/91ab198794dd01ef623f7ae7a6ae087c to your computer and use it in GitHub Desktop.
Save Gipetto/91ab198794dd01ef623f7ae7a6ae087c to your computer and use it in GitHub Desktop.
Single function Twilio Fax handling
/**
* !! Requires a SendGrid account & API Key.
* Sign up for the FREE account and create an API key.
* If you're receiving more than 100 faxes a day you
* shouldn't be entertaining the idea of a script like this...
*
* In the Function Instance view:
* - Paste this entire script
* - Set the url path for your Function to: /fax-to-email
*
* In the global functions Configure screen:
* - Ensure that "Enable ACCOUNT_SID and AUTH_TOKEN" is selected
* - Include `got` version `8.3.1` in Dependencies
* - Add environment variables and values for:
* - FAX_EMAIL_FROM
* - FAX_EMAIL_FROM_NAME
* - FAX_EMAIL_TO
* - SENDGRID_API_SEND_ONLY
*/
const got = require('got');
exports.handler = function(context, event, callback) {
const faxBaseUrl = `https://${context.DOMAIN_NAME}/fax-to-email`;
function redirectToMedia() {
let res = new Twilio.Response();
context.getTwilioClient().fax.v1.faxes(event.f).fetch().then((data) => {
res.setStatusCode(302);
res.appendHeader('Location', data.mediaUrl);
callback(null, res);
}).catch((err) => {
console.log(err);
res.setStatusCode(500);
res.setBody(err);
callback(null, res);
});
}
function receiveRedirect() {
const redirect = `
<Response>
<Receive action="${faxBaseUrl}"/>
</Response>
`.trim();
callback(null, redirect);
}
function receivedSendEmail() {
const emailBody = `You've got a new fax from "${event.From}". Link: ` +
`${faxBaseUrl}?f=${event.FaxSid}`;
const requestBody = {
personalizations: [{
to: [{
email: context.FAX_EMAIL_FROM,
name: context.FAX_EMAIL_FROM_NAME
}],
subject: `New fax from ${event.From}`
}],
from: {
email: context.FAX_EMAIL_TO,
name: 'Magic Fax Receiver'
},
content: [{
type: 'text/plain',
value: emailBody
}]
};
const request = {
headers: {
Authorization: `Bearer ${context.SENDGRID_API_SEND_ONLY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
};
got.post('https://api.sendgrid.com/v3/mail/send', request).then((response) => {
callback(null, new Twilio.twiml.MessagingResponse());
}).catch((err) => {
console.log(err);
callback(err);
});
}
switch (true) {
// not terribly scientific, but its good enough
case (event.f && event.f.length === 34):
redirectToMedia();
break;
case (event.Status && event.Status === 'received'):
receivedSendEmail();
break;
default:
receiveRedirect();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment