sendgrid-mail
Version:
The easiest way to send mail with sendgrid.
98 lines (85 loc) • 2.36 kB
JavaScript
const fs = require('fs')
const os = require('os')
const path = require('path')
const meow = require('meow')
const getStdin = require('get-stdin')
const debug = require('debug')('sendgrid-mail:cli')
const util = require('./util')
const init = async () => {
const helpText = fs.readFileSync(path.join(__dirname, '../man/doc.1')).toString()
const fromAddr = process.env.SENDGRID_MAIL_FROM || `${os.userInfo().username}@${os.hostname()}`
const replyToAddr = process.env.SENDGRID_MAIL_REPLYTO || process.env.REPLYTO || fromAddr
const cli = meow(helpText,
{
flags: {
apikey: {
type: 'string',
alias: 'k',
default: process.env.SENDGRID_API_KEY
},
suppressEmpty: {
type: 'boolean',
alias: 'E',
default: false
},
subject: {
type: 'string',
alias: 's',
default: ''
},
cc: {
type: 'string',
alias: 'c',
default: ''
},
bcc: {
type: 'string',
alias: 'b',
default: ''
},
html: {
type: 'boolean',
alias: 'h',
default: false
},
// Sendgrid wants from and replyTo
from: {
type: 'string',
default: fromAddr
},
replyTo: {
type: 'string',
default: replyToAddr
}
}
})
const body = await getStdin()
const contentType = cli.flags.html ? 'text/html' : 'text/plain'
const to = cli.input[0]
const from = util.parseEmail(cli.flags.from)
const replyTo = util.parseEmail(cli.flags.replyTo) || from
const options = {
// Sendmail-style options
to: util.parseList(to),
cc: util.parseList(cli.flags.cc),
bcc: util.parseList(cli.flags.bcc),
subject: cli.flags.subject,
body: body,
contentType: contentType,
suppressEmpty: cli.flags.suppressEmpty,
// Sendgrid API key
apikey: cli.flags.apikey,
// Sendgrid requires from, but replyTo is optional
from: from,
replyTo: replyTo
}
if (options.to.length + options.cc.length + options.bcc.length === 0) {
process.stdout.write(helpText)
process.exit(2)
}
debug(`command line options: ${JSON.stringify(options, null, 2)}`)
return options
}
module.exports = {
init: init
}