Created
April 8, 2024 16:57
-
-
Save kevboutin/52a0199d38865341dad8280418318f3d to your computer and use it in GitHub Desktop.
SendGrid email utility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const sgMail = require('@sendgrid/mail'); | |
sgMail.setTimeout(40000); | |
const TAG = 'emailUtility'; | |
const DEFAULT_SENDER = '[email protected]'; | |
/** | |
* 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