Skip to main content
267

Send VoiceMail (audio) to Email

Created
Active
Viewed 250 times
1 min read
Part of Twilio Collective
0

I found that it was difficult getting access to VoiceMail made in the Twilio Studio so I made a small script to send the audio file to one or more e-mail specified in the studio parameters.

Use this as your starting point to get this setup: https://www.twilio.com/blog/forward-voicemail-recordings-to-email

I swapped one context key with an event key so you can change the e-mail that the message is sent to, and it can be sent to more than one person by separating them with commas, no spaces.

Here is the code, followed by a second block for a delay function since the VoiceMail audio wasn't ready to be retrieved immediately after it was finished. This was built using JavaScript using Node JS (v18).

I cleaned up the code to make it easier to read. The two parts is to get the file, in base64, then send it via e-mail.

exports.handler = function(context, event, callback) {

    const sgMail = require('@sendgrid/mail');
    var request = require('request').defaults({
        encoding: null
    });

    function doCall(callback) {
        request.get({
                url: event.url + '.mp3',
                headers: {
                    "Authorization": "Basic " + new Buffer.from(context.ACCOUNT_SID + ":" + context.AUTH_TOKEN).toString("base64")
                }
            },
            function(error, response, body) {
                callback(Buffer.from(body).toString('base64'));
            });
    }

    doCall(function(response) {
        sgMail.setApiKey(context.SENDGRID_API_SECRET);
        const msg = {
            to: event.email.split(','),
            from: context.FROM_EMAIL_ADDRESS,
            subject: `New Voicemail from: ${event.From}`,
            text: 'See attachment to review the voicemail.',
            attachments: [{
                content: response,
                filename: "Voicemail.mp3",
                type: "audio/mpeg",
                disposition: "attachment"
            }]
        };
        sgMail.send(msg).then(response => {
            callback();
        });
    })
}

Delay Function

const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));
exports.handler = async (context, event, callback) => {
    const delay = event.delay || 5000;
    await sleep(delay);
    return callback(null, `Timer up: ${delay}ms`);
};