Sendgrid-nodejs: 400 error when attempting to send email in POST request

Created on 14 Oct 2016  路  10Comments  路  Source: sendgrid/sendgrid-nodejs

I have a single buy button on my site and when it's clicked, it sends a message to /charge and Stripe handles the payment processing. I also create a user in my mongoose database.

After that, I have a welcome email that I'd like to send to the new customer, but it never gets sent. I see a 400 error in console though. Here is my code:

  // Checkout
  app.post("/charge", (req, res) => {

    // Get the credit card details submitted by the form
    const
      token = req.body.stripeToken,
      email = req.body.stripeEmail;

    stripe stuff...



    const emailRequest = sg.emptyRequest({
      method: "POST",
      path: "/v3/mail/send",
      body: {
        personalizations: [
          {
            to: { email: email },
            subject: "Welcome to Awesome!",
          },
        ],
        from: {
          email: "[email protected]",
          name: "Awesome"
        },
        content: [{
          type: "text/plain",
          value: "We're happy to have you and can't wait for you to get started."
        }]
      }
    });

    sg.API(emailRequest).then(response => {
      console.log("01");
      console.log(response.statusCode);
      console.log("02");
      console.log(response.body);
      console.log("03");
      console.log(response.headers);
      console.log("04");

      res.redirect("/thanks");
    }).catch(error => {
      // error is an instance of SendGridError
      // The full response is attached to error.response
      console.log("05");
      console.log(error.response.statusCode);
    });
  });

Can anyone see what I'm doing wrong?

question

Most helpful comment

That is extremely strange...

Oh well, it works now so I'm happy. Thanks for the update!

All 10 comments

Is it because I'm sending a POST inside of a POST?

Wow, figured out the issue, thanks to error.response. Whatever example I copied from the official SendGrid repo on npm fucked me over. Apologies for the language but this was frustrating. The body of my message was configured improperly. Here is the correct configuration:

body: {
  from: {
    email: "[email protected]",
    name: "Awesome"
  },
  personalizations: [{
    to: [{ email: email }]
  }],
  subject: "Welcome to Awesome!",
  content: [{
    type: "text/plain",
    value: "We're happy to have you and can't wait for you to get started."
  }]
}

It'd be great if all examples were up to date.

Hello @NetOperatorWibby,

Thanks for the follow up!

No need to apologize, we should do better.

Could you please point to me to where you copied the code from? I looked here, but that code works.

I'll make sure it's updated along with any other instances of that example code.

It was actually the example in the README, "Without Mail Helper Class" https://github.com/sendgrid/sendgrid-nodejs#without-mail-helper-class

I still have Terminal open so I can share the error message that appeared:

statusCode: 400, body: '{"errors":[{"message":"Invalid type. Expected: array, given: object.","field":"personalizations","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#-Personalizations-Errors"}]}'

Thanks for the quick response!

That is actually the same code that is on npm.

To verify, I just cut and pasted that and it worked for me, here is my exact code:

var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
var request = sg.emptyRequest({
  method: 'POST',
  path: '/v3/mail/send',
  body: {
    personalizations: [
      {
        to: [
          {
            email: '[email protected]',
          },
        ],
        subject: 'Hello World from the SendGrid Node.js Library!',
      },
    ],
    from: {
      email: '[email protected]',
    },
    content: [
      {
        type: 'text/plain',
        value: 'Hello, Email!',
      },
    ],
  },
});

//With callback
sg.API(request, function(error, response) {
  if (error) {
    console.log('Error response received');
  }
  console.log(response.statusCode);
  console.log(response.body);
  console.log(response.headers);
});

What version of the library are you using?

Hmm, it's certainly possible I messed something up and managed to fix it while changing this particular piece of code. My version is 4.5.0.

I see you are using the promises, so I also tried that and I can not reproduce the error :(

var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
var request = sg.emptyRequest({
  method: 'POST',
  path: '/v3/mail/send',
  body: {
    personalizations: [
      {
        to: [
          {
            email: '[email protected]',
          },
        ],
        subject: 'Hello World from the SendGrid Node.js Library!',
      },
    ],
    from: {
      email: '[email protected]',
    },
    content: [
      {
        type: 'text/plain',
        value: 'Hello, Email!',
      },
    ],
  },
});

sg.API(request)
  .then(response => {
    console.log(response.statusCode);
    console.log(response.body);
    console.log(response.headers);
  })
  .catch(error => {
    //error is an instance of SendGridError
    //The full response is attached to error.response
    console.log(error.response.statusCode);
  });

Response:

202

{ server: 'nginx',
  date: 'Fri, 14 Oct 2016 18:21:48 GMT',
  'content-type': 'text/plain; charset=utf-8',
  'content-length': '0',
  connection: 'close',
  'x-message-id': 'YgeEUQTbRgu22R9kGiP1Wg',
  'x-frame-options': 'DENY' }

And the email is delivered.

Thanks for taking extra time to verify :)

You may want to check out release v4.6.0. It has a small update that might be useful to you: https://github.com/sendgrid/sendgrid-nodejs/releases

Welcome to SendGrid!

That is extremely strange...

Oh well, it works now so I'm happy. Thanks for the update!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wooyah picture wooyah  路  4Comments

nicoasp picture nicoasp  路  3Comments

thinkingserious picture thinkingserious  路  4Comments

polkhovsky picture polkhovsky  路  3Comments

Loriot-n picture Loriot-n  路  4Comments