Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twilio - Send email from function

Is there a way to send email from Twilio function? I understand that we can use sendgrid. I am looking a simpler solution.

like image 594
arun kumar Avatar asked Mar 21 '19 16:03

arun kumar


People also ask

Can we use Twilio to send email?

SendGrid is a cloud-based SMTP provider owned by Twilio that allows you to send email without having to maintain email servers. Only the SendGrid PHP package and a SendGrid API key are required to enable sending of emails within your application. First you need to generate a SendGrid API key.

Is twilio and SendGrid the same?

With SendGrid now a part of Twilio, our goal is to provide a complete platform for every form of customer engagement,” said Jeff Lawson, Twilio co-founder and CEO. “Through our mutual developer-first approach, we empower the builders of the world to create magical customer experiences unique to every interaction.”

Can Twilio convert email to SMS?

Now, with the power of Twilio SendGrid email and Twilio SMS, you can quickly set up your own two-way email to SMS forwarding solution.


1 Answers

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: '[email protected]',
      from: '[email protected]',
      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 [email protected] 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.

Twilio 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. :)

like image 131
stefan judis Avatar answered Sep 29 '22 12:09

stefan judis