I'm trying to send dynamic emails with Twilio SendGrid Rest API with Nodejs and handlebars. I have created my own custom template and placed the design in a file template.html. I'm successfully using this template using Nodemailer and SMTP-transport. But when trying to send it with SendGrid I get error :
ResponseError: Forbidden at node_modules/@sendgrid/client/src/classes/client.js:146:29 at processTicksAndRejections (internal/process/task_queues.js:95:5) { code: 403, response: { headers: { server: 'nginx', date: 'Wed, 07 Sep 2022 17:03:16 GMT', 'content-type': 'application/json', 'content-length': '281', connection: 'close', 'access-control-allow-origin': 'https://sendgrid.api-docs.io', 'access-control-allow-methods': 'POST', 'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl', 'access-control-max-age': '600', 'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html', 'strict-transport-security': 'max-age=600; includeSubDomains' }, body: { errors: [Array] } } }
This is my nodejs
const handlebars = require('handlebars');
const path = require('path');
const fs = require('fs');
const sendgrid = require('@sendgrid/mail')
sendgrid.setApiKey(sendgrid_api_key);
//readhtmfile
var readHTMLFile = function (path, callback) {
fs.readFile(path, { encoding: 'utf-8' }, function (err, html) {
if (err) {
throw err;
callback(err);
}
else {
callback(null, html);
}
});
};
//dynamic variable received from client
var name = 'John Doe';
//email user
readHTMLFile(path.join(__dirname, '/', 'template.html'), function (err, html) {
var template = handlebars.compile(html);
var replacements = {
email_title: 'Welcome email',
email_body: 'Welcome to our website '+name
};
var htmlToSend = template(replacements);
var mailOptions = {
from: '"Company Website" <verified_sendgrid_email@company.com>', // sender address
to: email, // list of receivers
subject: "Welcome email ", // Subject line
html: htmlToSend, // html body
};
sendgrid.send(mailOptions, function (error, response) {
if (error) {
console.log(error);
} else {
console.log(response);
}
});
});