Skip to content

Instantly share code, notes, and snippets.

@kevboutin
Created April 8, 2024 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevboutin/52a0199d38865341dad8280418318f3d to your computer and use it in GitHub Desktop.
Save kevboutin/52a0199d38865341dad8280418318f3d to your computer and use it in GitHub Desktop.
SendGrid email utility
const sgMail = require('@sendgrid/mail');
sgMail.setTimeout(40000);
const TAG = 'emailUtility';
const DEFAULT_SENDER = 'donotreply@somedomain.com';
/**
* Send an email.
*
* @param {object} toSend The email envelope object to send.
* @param {string} apiKey The email API key.
* @return {Promise} A promise.
*/
exports.send = (toSend, apiKey) =>
new Promise((resolve, reject) => {
console.log(`${TAG}::Attempting to send:`, JSON.stringify(toSend, null, 2));
sgMail.setApiKey(apiKey);
sgMail
.send(toSend)
.then((response) => {
console.log(`${TAG}::Successful email send response:`, response);
resolve(response);
})
.catch((error) => {
console.error(`${TAG}::Failed to send an email.`, JSON.stringify(error, null, 2));
reject(error);
});
});
/**
* Compose a notification email envelope for sending.
*
* @param {string} subject The subject of the email.
* @param {string} content The content of the email.
* @param {string} recipient The recipient email address.
* @param {string} sender The sender email address. If null, this will default to the configured default value.
* @return {object} The email object.
*/
exports.composeEmail = (subject, content, recipient, sender) => {
let sendFrom = sender;
if (!sender) {
sendFrom = process.env.EMAIL_FROM || DEFAULT_SENDER;
}
// Return the email envelope object.
return {
to: recipient,
from: sendFrom,
subject,
text: 'Plain text is not supported. Please use an email client that is capable of rendering HTML.',
html: content,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment