sendgrid-templated extends @sendgrid/client and @sendgrid/helpers to allow for easy use with html templates and data injection.
Use npm i sendgrid-templated to install the package via NPM.
import Email from "sendgrid-templated";
const email = new Email({
apiKey: "SENDGRID_API_KEY",
from: { email: "[email protected]", name: "Jane Doe" },
to: { email: "[email protected]", name: "John Doe" },
subject: "Welcome",
template: {
filePath: path.join(__dirname, "templates/welcome.html"),
data: { firstName: "John", message: "Thanks for joining!" }
}
});
email
.send()
.then(() => {
// Success!
})
.catch(err => {
// Handle err
});Assuming templates/welcome.html looks something like:
<div>
<h1>Welcome, {{firstName}}!</h1>
<div>{{message}}</div>
</div>The config object supplied to the contructor has the following options:
apiKey: The API key you receive from sendgrid. Defaults toprocess.env.SENDGRID_API_KEYfrom: Object containing theemailand [optional]namefor the email'sfrominfo. Defaults toprocess.env.SENDGRID_FROM_EMAILandprocess.env.SENDGRID_FROM_NAMEto: Object containing theemailand [optional]namefor the email'stoinfo.subject: The subject of the email.template: [optional] Object containing info about the template to be used. SeeTemplate Config Optionsbelow for more details.
The template config object has the following options:
filePath: The path to the html file to be used as the email template.data: [optional] Object containing key/value pairs of injections to be made into the template.wrappers: [optional] A tuple of opening and closing char(s) to denote a template variable. (e.g.["%", "%"]would denote a template var of format%firstName%)
Contributions are welcome!
To continue development on sendgrid-templated, clone this repo, then run npm i to install all necessary dependencies.
You can run npm build to build the project, and npm test to run tests.