expresstwiliosendgrid

Subject Not Set in Emails Using @sendgrid/mail with Express Backend


I'm using the @sendgrid/mail library in my Express backend to send emails when an order is purchased. However, the email subject does not appear in the sent emails. I've tried setting the subject both as static text and using dynamic text, but neither seems to work.

Here’s the relevant part of the code:

await sgMail.send({
  to: result.contactEmail.trim(),
  from: "no-reply@mailinator.com",
  subject: "Order Confirmation",
  templateId: sendgrid_template_id,
  dynamicTemplateData: {
    ...result,
  },
});

The structure is the same as given in the official documentation

Ideally, I want the subject line to include the confirmation number, like Order Confirmation #${confirmationNumber}.

Additional Information:

I have set dynamicTemplateData with other email data, but there is no subject field in the result object or the template that might override the email subject.

Also, no personalizations are being used in this configuration to harden the problem.

Environment Details:

Node.js version: 16.20.2

Express version: ~4.17.1

@sendgrid/mail version: 7.7.0

Thanks!

All of these questions from StackOverflow are similar to mine, but not the same:

Could anyone help me understand why the subject is not being set and how I can dynamically include the confirmation number in the subject line?


Solution

  • When using dynamic templating we need to set the subject as dynamic data.

    On the template, set the subject with a handlebars variable, something like {{ subject }}.

    Note: spaces are important!

    subject var set on sendgrid's UI

    Then, on your code, just move the subject to the dynamicTemplateData:

    await sgMail.send({
      to: result.contactEmail.trim(),
      from: "no-reply@mailinator.com",
      templateId: sendgrid_template_id,
      dynamicTemplateData: {
        subject: "Order Confirmation",
        ...result,
      },
    });