AbdulAzeez Olanrewaju
AbdulAzeez Olanrewaju

Reputation: 1078

Sendgrid with Nodejs backend

I am trying to use SendGrid Mail service to send mail and it throw error 400 in the nodejs server.

Is this from Sendgrid or frontend?

I also got the content in the quill rich text editor, because I'm using it.

Every time I get "BAD REQUEST" in the server, but it's sent like [object null reference].

Mail.js, where I'm creating the function:

// SendGrid
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

// cb means callback for error or success
const sendEmail = (email, subject, content, cb) => {
  const msg = {
    from: email,
    to: '[email protected]',
    cc: '[email protected]',
    subject: subject,
    text: content,
    // html: content,
  };
  sgMail
    .send(msg)
    .then(() => {
      console.log('Email sent');
      // console.log(cb(null, data));
    })
    .catch((error) => {
      console.error(error);
      // console.log(cb(error, null));
    });
};

module.exports = sendEmail;

index.js //server (backend)

const express = require('express');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const cors = require('cors');
const path = require('path');
const dotenv = require('dotenv');
const app = express();

dotenv.config({ path: './config/config.env' });

// bring in SendEmail
const sendMail = require('./mail');

// View engine setup
app.engine('handlebars', exphbs({ defaultLayout: false }));
app.set('view engine', 'handlebars');

// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));

// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'contact.html'));
  // res.sendFile('contact.html', { root: '.' });
});
//old key
//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
app.post('/send', (req, res) => {
  const { subject, to, content, email } = sendMail;
  sendMail(email, to, subject, content, () => {
    if (err) {
      console.error(err.ResponseError);
      res.status(400).json({ message: 'Internal Error' });
    } else if (res.status(500)) {
      console.log('Error Something happned!');
    } else {
      console.log(data);
      res.json({ message: 'Message Sent' });
    }
  });
  console.log(req.body);
});

// Setting PORT from .env
const PORT = process.env.PORT || 5000;

// console.log(process.env);
app.listen(PORT, () => console.log(`Server Started on ${PORT}`));

app.js (frontend)

const getIds = (id) => {
  return document.getElementById(id);
};

const form = document.querySelector('#form');

form.addEventListener('submit', (e) => {
  e.preventDefault();
  const from = getIds('from').value;
  const subject = getIds('subject').value;
  const emailFormat = quill.root.innerHTML;
  const content = (getIds('content').value = emailFormat);
  const data = {
    from,
    subject,
    content,
  };

  axios
    .post('/send', data, {
      headers: {
        'Content-Type': 'application/json',
      },
    })
    .then((res) => {
      form.reset();
      quill.setContents([{ insert: '\n' }]);
      M.toast({ html: 'Email Sent!!' });
      console.log(res);
    })
    .catch((err) => console.log(err));
});

Upvotes: 1

Views: 2028

Answers (1)

CyberEternal
CyberEternal

Reputation: 2545

You can use @sendgrid/mail NPM module.

import sgMail from '@sendgrid/mail';
const setApiKey = () => sgMail.setApiKey(process.env.SENDGRID_API_KEY);

export const sendEmail = ({
  emailTo, data, emailFrom
}) => {
  return new Promise(async (resolve, reject) => {
    try {
      setApiKey();
      const msg = {
        to: [emailTo],
        from: emailFrom, // Use the email address or domain you verified above
        subject: 'Sending with Twilio SendGrid is Fun',
        html: '<strong>and easy to do anywhere, even with Node.js</strong>',
      };
      const result = await sgMail.send(msg);
      resolve(result);
    } catch (_e) {
      console.log('Error in sendEmail: ', _e.response.body);
      reject(_e.response.body);
    }
  });
};

For your case use this one

    import sgMail from '@sendgrid/mail';
const setApiKey = () => sgMail.setApiKey(process.env.SENDGRID_API_KEY);

export const sendEmail = (email, subject, content) => {
  return new Promise(async (resolve, reject) => {
    try {
      setApiKey();
      const msg = {
        from: email,
        to: '[email protected]',
        cc: '[email protected]',
        subject: subject,
        text: content,
      };
      const result = await sgMail.send(msg);
      resolve(result);
    } catch (_e) {
      console.log('Error in sendEmail: ', _e.response.body);
      reject(_e.response.body);
    }
  });
};


app.post('/send', (req, res) => {
  try {
    const { email, subject, content } = req.body;
    await sendMail(email, subject, content);
    res.json({ message: 'Message Sent' });
  } catch (error) {
    res.status(400).json({ message: 'Something went wrong' });
  }
  console.log(req.body);
});

Upvotes: 1

Related Questions