Skip to content

Instantly share code, notes, and snippets.

@codediodeio
Last active January 23, 2021 17:06
Show Gist options
  • Save codediodeio/f50c2d2f3cc0243814a40f71f221d2ab to your computer and use it in GitHub Desktop.
Save codediodeio/f50c2d2f3cc0243814a40f71f221d2ab to your computer and use it in GitHub Desktop.

Revisions

  1. codediodeio revised this gist Jun 15, 2017. No changes.
  2. codediodeio created this gist Jun 15, 2017.
    51 changes: 51 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    var functions = require('firebase-functions');

    const sendgrid = require('sendgrid')
    const client = sendgrid("YOUR_SG_API_KEY")

    function parseBody(body) {
    var helper = sendgrid.mail;
    var fromEmail = new helper.Email(body.from);
    var toEmail = new helper.Email(body.to);
    var subject = body.subject;
    var content = new helper.Content('text/html', body.content);
    var mail = new helper.Mail(fromEmail, subject, toEmail, content);
    return mail.toJSON();
    }


    exports.httpEmail = functions.https.onRequest((req, res) => {
    return Promise.resolve()
    .then(() => {
    if (req.method !== 'POST') {
    const error = new Error('Only POST requests are accepted');
    error.code = 405;
    throw error;
    }


    const request = client.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: parseBody(req.body)
    });

    return client.API(request)


    })
    .then((response) => {
    if (response.body) {
    res.send(response.body);
    } else {
    res.end();
    }
    })

    .catch((err) => {
    console.error(err);
    return Promise.reject(err);
    });


    })