otmezger
otmezger

Reputation: 10774

how to send an email via sendgrid API V3 using templates, full example

I'm reading through the send grid documentation about templates here and could find this:

You can send transactional templates using one of three ways:

  1. Using the SMTP Relay
  2. Including the template ID in the templates parameter of the Web API v3 Mail Send endpoint
  3. Using the x-smtp api parameter in the Web API v2 Mail Send endpoint

In node.js I have access to their JS SDK. However, In API the documentation it is explained only how to use the first method (SMTP relay). In the documentation of the JS SDK there is no option for sending emails using a template.

Where can I find a complete example of how to use the JS SDK of send grid to send an email using a template?

thanks.

Upvotes: 0

Views: 3177

Answers (1)

otmezger
otmezger

Reputation: 10774

It looks like there is an example buried in an issue on the Github repository: https://github.com/sendgrid/sendgrid-nodejs/issues/252#issuecomment-232473145

var sg = require('sendgrid').SendGrid("SendGrid API Key" or <environment variable>)

function sendEmail(tempID){
    var helper = require('sendgrid').mail;
    from_email = new helper.Email("[email protected]")
    to_email = new helper.Email("[email protected]")
    subject = "Dummy Subject"
    content = new helper.Content("text/html", "dummy content")
    mail = new helper.Mail(from_email, subject, to_email, content)

    substitution = new helper.Substitution("-name-", "User's Name")
    mail.personalizations[0].addSubstitution(substitution)
    mail.setTemplateId(tempID)
    var requestBody = mail.toJSON()
    var requestPost = JSON.parse(JSON.stringify(sg.emptyRequest()))
    requestPost.method = 'POST'
    requestPost.path = '/v3/mail/send'
    requestPost.body = requestBody
    sg.API(requestPost, function (response) {
       console.log(response.statusCode)
       console.log(response.body)
       console.log(response.headers)
  })
}

In my case, it worked fine. I get the email but response is always empty.

Upvotes: 1

Related Questions