UNPKG

sendgrid-mail

Version:

The easiest way to send mail with sendgrid.

72 lines (62 loc) 1.85 kB
'use strict' const debug = require('debug')('sendgrid-mail:sendgrid') const bent = require('bent') const _ = require('lodash') const util = require('./util') const sgPost = bent('POST', 'https://api.sendgrid.com/v3/', 202) const chattySgPost = async (reqHeaders, reqBody) => { debug('calling sendgrid /mail/send api') debug(`request headers: ${util.inspect(reqHeaders)}`) debug(`request body: ${util.inspect(reqBody)}`) try { const resp = await sgPost('mail/send', reqBody, reqHeaders) const respStatus = resp.statusCode const respText = await resp.text() debug(`${respStatus} response: ${respText}`) return respText } catch (error) { const errorStatus = error.statusCode const errorText = await error.text() debug(`error response ${errorStatus}: ${errorText}`) debug('re-throwing...') throw error } } const sendMail = async (options = {}) => { if (options.suppressEmpty && _.isEmpty(options.body)) { throw new Error('Refusing to send mail with empty body when suppressEmpty is true') } const sgOptions = { personalizations: [ { to: options.to, cc: options.cc, bcc: options.bcc } ], from: options.from, reply_to: options.replyTo, subject: options.subject, content: [ { type: options.contentType || 'text/plain', value: options.body } ] } sgOptions.personalizations = sgOptions.personalizations.filter(obj => { const retVal = Object.assign(obj) for (const field of ['to', 'cc', 'bcc']) { if (_.isEmpty(retVal[field])) { delete retVal[field] } } return retVal }) const sgHeaders = { Authorization: `Bearer ${options.apikey}`, 'Content-Type': 'application/json' } await chattySgPost(sgHeaders, sgOptions) } module.exports = sendMail