skip to Main Content

I am trying to send an email using nodejs on a vercel host.

I am getting a bad request using the sendgrid/mail api. It looks as though it is not creating the header info in the request to Sendgrid.

When I dump the message, is it just the json info i am sending.

Here is the code i am using.

const sgMail = require('@sendgrid/mail')

const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY;

export default function (req, res) {

    const mailData = {
        from: '[email protected]',
        to: req.body.email,
        subject: 'Message to Full On Consulting',
        text: req.body.message,
        html: '<div>'+req.body.message+'</div>'
    }
    const {
      classes: {
        Mail,
      },
    } = require('@sendgrid/helpers');
    const mail = Mail.create(mailData);
    const body = mail.toJSON();
    console.log("======================================== ");
    console.log("RAW BODY: " + JSON.stringify(body));
    console.log("======================================== ");

    sendMail(mailData)
    .then((result) => {
            console.log('Email sent...', result);
            res.status(200).json({ status: 'SUCCESS' })
        })
    .catch((error) => console.log('Error ... ' + error.message));
}

async function sendMail(mailData) {
  try {

    var promise = new Promise( (resolve, reject) => {

      sgMail.setApiKey(SENDGRID_API_KEY)

      const msg = {
        to: mailData.to, // Change to your recipient
        from: mailData.from, // Change to your verified sender
        subject: mailData.subject,
        text: mailData.text,
        html: mailData.html,
      }
      console.log("API KEY: " + SENDGRID_API_KEY);
      console.log(JSON.stringify(msg));

      sgMail
        .send(msg)
        .then(() => {
          console.log('Email sent');
        })
        .catch((error) => {
          console.error(error);
          console.log('RECEIVED ERROR')
        })
    });

     //promise.then( result => {
     // console.log("PRomise Success ...");
     //}, function(error) {
     // console.log("Promise Failure...");
     //});

  } catch (error) {
        console.log("CATCH ERROR: " + error)
        return error;
  }
}

Here is the Error

ResponseError: Bad Request
    at node_modules/@sendgrid/client/src/classes/client.js:146:29
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 400,
  response: {
    headers: {
      server: 'nginx',
      date: 'Sat, 30 Oct 2021 13:51:20 GMT',
      'content-type': 'application/json',
      'content-length': '219',
      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] }
  }
}

3

Answers


  1. Chosen as BEST ANSWER

    I was not passing the info correctly from my front-end form which was causing the issue.


  2. You can try expanding the response.body object and look for the error messages along with the help messages that you are getting.

    Login or Signup to reply.
  3. step 1: you should verify sendgrid account setting->sender athentication ->verify single sender verification

    step 2: sendgrid From Email : "[email protected]"

    step 3: to email && env file config

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search