sendgrid-nodejs icon indicating copy to clipboard operation
sendgrid-nodejs copied to clipboard

Transactional Template Email is not getting delivered in the Firebase cloud function.

Open geecat opened this issue 6 years ago • 6 comments

I am integrating SendGrid email in the Firebase cloud function. I have authenticated the domain in SendGrid console

Screenshot 2020-09-28 at 1 06 10 PM

Below are two ways I'm trying.

import mail from '@sendgrid/mail';
mail.setApiKey(process.env.SENDGRID_API_KEY);
  1. Working example:
               
               console.log('Sending Email2 example');
                const msg2 = {
                to: '[email protected]',
                from: '[email protected]',
                subject: 'Hello world',
                text: 'Hello plain world!',
                html: '<p>Hello HTML world!</p>',
                };
                await mail.send(msg2);

                console.log('Sending Email2 example');

               This email is getting delivered in my mailbox.
  1. Not working:
           console.log('Sending Email1 example');
                const msg1 = {
                    to: '[email protected]',
                    from: '[email protected]',
                    templateId: 'd-58ce8e494aac482595ff1197eeb2697e',
                    dynamicTemplateData: {
                        subject: 'Testing Templates',
                        name: 'Some One',
                        city: 'Denver',
                    },
                    };
                await  mail.send(msg1).then(() => console.log('Mail1 sent successfully'))
                 .catch(error => {
                   console.error(JSON.stringify( error));
               
                   if (error.response) {
                     console.error(JSON.stringify( error.response.body))
                   }
                 });

This is the same example as mentioned here https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/use-cases/transactional-templates.md Below is screen shot of the console.

Screenshot 2020-09-28 at 12 52 12 PM Below is sc Screenshot 2020-09-28 at 12 51 28 PM Screenshot 2020-09-28 at 12 52 26 PM

what I am doing wrong here? The first one is working fine but the second email is not getting delivered.

When I send emails through a dynamic template I get success as a response but emails do not get delivered. also if I provide wrong templateId in that case also I am getting a success response, I wonder how it's possible.

Here is my ts config

 {
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strictNullChecks": false,
    "strict": false,
    "target": "es2017",
    "resolveJsonModule": true,
    "esModuleInterop": true  
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}      

and package.json

  {
    "name": "functions",
    "scripts": {
      "lint": "tslint --project tsconfig.json",
      "build": "tsc",
      "serve": "npm run build && firebase emulators:start --only functions",
      "shell": "npm run build && firebase functions:shell",
      "start": "npm run shell",
      "deploy": "firebase deploy --only functions",
      "logs": "firebase functions:log"
    },
    "engines": {
      "node": "10"
    },
    "main": "lib/index.js",
    "dependencies": {
      "@google-cloud/pubsub": "^2.1.0",
      "@sendgrid/mail": "^7.2.6",
      "axios": "^0.19.2",
      "firebase-admin": "^8.9.0",
      "firebase-functions": "^3.11.0",
      "grpc": "^1.24.3"
    },
    "devDependencies": {
      "tslint": "^5.12.0",
      "typescript": "^3.2.2",
      "firebase-functions-test": "^0.1.6"
    },
    "private": true
  }

geecat avatar Sep 28 '20 07:09 geecat

Hello @geecat ,

It looks like you have it setup properly to me; however, I was unable to reproduce locally.

I used the same HTML templates as you and here is the code I used:

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
    to: '[email protected]',
    from: '[email protected]',
    templateId: 'd-mytemplate-id',
    dynamicTemplateData: {
      subject: 'Testing Templates',
      name: 'Some One',
      city: 'Denver',
    },
};
(async () => {
  try {
    await sgMail.send(msg);
  } catch (error) {
    console.error(error);

    if (error.response) {
      console.error(error.response.body)
    }
  }
})();

For the emails that get sent successfully but don't see them delivered, do you see them in your email activity view?

With best regards,

Elmer

thinkingserious avatar Sep 29 '20 00:09 thinkingserious

Hi Elmer, Thanks for replying. I changed the SendGrid import to Typescript way and I deleted all the key API key and created a new one and it started working.

I tried multiple ways of integrating the send mail and all are working fine now.

  1. Integrating sendgrid mail client import mail from '@sendgrid/mail'; const API_KEY = functions.config().sendgrid.key; mail.setApiKey(API_KEY);
  2. Calling https://api.sendgrid.com/v3/mail/send with post option.
const sendEmail = async (toEmail, toName, templateId) =>  {
  try{
      const bearerKey = "Bearer ".concat(API_KEY.toString());
      console.log('Mail sent iitiated', 'Bearer '+process.env.SENDGRID_API_KEY, API_KEY,bearerKey)
      let options = {
      headers: 
      { 'content-type': 'application/json',
      authorization: bearerKey }};
      let data = {
          personalizations: [
            {
              to: [
                {
                  email: toEmail,
                  name: toName
                },
              ],
            }
          ],
          from: {
            email: "[email protected]",
            name: "Name"
          },
          template_id : templateId
        };
      await axios.post('https://api.sendgrid.com/v3/mail/send', data,options);
      console.log('Mail sent successfully')
     
         
  }catch(e){
      console.error('Error sending in email');
  }
  
 };

Both of them are working now.

I can not see those emails in the email activity view?

I have one question why do I get a success response when I send the wrong template id?

geecat avatar Sep 29 '20 13:09 geecat

I'm glad to hear you were able to get things working! And thanks for sharing your results!

Here is what I get when I use the wrong template ID: (I'm using the same code as above, I just removed a character from the temaplateId string)

ResponseError: Bad Request
    at node_modules/@sendgrid/client/src/classes/client.js:133:29
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  code: 400,
  message: 'Bad Request',
  response: {
    headers: {
      server: 'nginx',
      date: 'Tue, 29 Sep 2020 21:05:24 GMT',
      'content-type': 'application/json',
      'content-length': '866',
      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'
    },
    body: { errors: [Array] }
  }
}
{
  errors: [
    {
      message: "The template_id must be a valid GUID, you provided 'd-baddb3551a76483598ece251aa7faea'.",
      field: 'template_id',
      help: 'http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.template_id'
    },
    {
      message: 'The subject is required. You can get around this requirement if you use a template with a subject defined or if every personalization has a subject defined.',
      field: 'subject',
      help: 'http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.subject'
    },
    {
      message: 'Unless a valid template_id is provided, the content parameter is required. There must be at least one defined content block. We typically suggest both text/plain and text/html blocks are included, but only one block is required.',
      field: 'content',
      help: 'http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.content'
    }
  ]
}

thinkingserious avatar Sep 29 '20 21:09 thinkingserious

@thinkingserious When you delete a character the template id is not a valid GUID, hence you are getting error. If you just replace the character with something else request will be accepted and no mail will be sent.

geecat avatar Sep 29 '20 21:09 geecat

Issue here: https://github.com/sendgrid/sendgrid-nodejs/issues/778

SendGrid does not verify the template ID on the mail-send call to reduce backend complexity/response times.

childish-sambino avatar Sep 30 '20 16:09 childish-sambino

@childish-sambino Thank you for clarification. Since my issue is resolved. I am closing this.

geecat avatar Sep 30 '20 18:09 geecat