Skip to content

SendGrid Integration

SendGrid is a email delivery with cloud-based solution and can be used to send transactional and marketing email. Stack9 allows integration with Sendgrid in order to send emails using SendGrid custom templates.

Environment variables

These enviroment variables should be configured in order to start using sendgrid in stack9

SEND_GRID_API_KEY // SendGrid API KEY SEND_GRID_SENDER_EMAIL // Must be a valid sender email configured in Sendgrid SEND_GRID_SENDER_NAME // Sender Name

Stack9-core

IEmailService

  • Send mail
/**
* @param mail
*/
send(mail: MailDataRequired): Promise<any>;
  • Retrieve a single transactional template. (StackCore 2.0.0 and above)
/**
* @param templateId
*/
getTemplateById(templateId: string): Promise<{ [key: string]: any }>;

Usage

Send a single email to a single recipient

await services.email
  .send({
     from: { email: "test@test.com", name: "Stack9" }, // optional, if didn't specified, it will use the env environments
     to: { email: "mail1@test.com", name: "Mail1" },
     templateId: "1234567899", // transactional template id in sendgrid
     dynamicTemplateData: {
       firstname: "Name",
       address: "St test",
       //... any data goes here
     }
  })
  .catch((error) =>
  logger.error(error, "Error email")
);

Send a single email to multiple recipients

await services.email
  .send({
     from: { email: "test@test.com", name: "Stack9" }, // optional, if didn't specified, it will use the env environments
     to: [
       { email: "mail1@test.com", name: "Mail1" }, 
       { email: "mail2@test.com", name: "Mail2" }
     ],
     templateId: "1234567899", // transactional template id
     dynamicTemplateData: {
       firstname: "Name",
       address: "St test",
       //... any data goes here
     }
  })
  .catch((error) =>
  logger.error(error, "Error email")
);

Retrieve a single transactional template. (StackCore 2.0.0 and above)

try {
  await services.email.getTemplateById(templateIdToUse);
} catch (e) {
  logger.error(
    { SendGridTemplateId: templateIdToUse, Exception: e },
    'Send Grid Template {SendGridTemplateId} could not be found. {Exception}',
  );
}