user2799827
user2799827

Reputation: 1127

How to use SendGrid to send email in ExpressJS

I am attempting to follow the docs at https://sendgrid.com/docs/for-developers/sending-email/v3-nodejs-code-example/. As a test, I am attempting to send email when a user creates a post.

here is my code:

in my package.json:

...
"dependencies": {
    "@sendgrid/client": "^6.4.0",
...

in posts.js routing:

const express = require('express');
const auth = require('../middlewares/authenticate');
const User = require('../models/User');
const Post = require('../models/Post');
const sgMail = require('@sendgrid/client');

let router = express.Router();

//POST new post route 
router.post('/', async (req, res, next) => {
  await Post.query()
  .insert({
    body: req.body.post.body,
    users_id: req.body.post.userId,
    groups_id: req.body.post.groupId
  }) 
  res.json({
    success: true, message: 'ok' 
  });   // respond back to request
  sgMail.setApiKey(process.env.SENDGRID_API_KEY);
  console.log('this is the sendgrid api key: ', process.env.SENDGRID_API_KEY)
  const msg = {
    to: '[email protected]',
    from: '[email protected]',
    subject: 'User just posted a message',
    text: req.body.post.body,
    html: '<strong>Can we see the message?</strong>',
  };
  console.log('this is the msg 2b sent: ', msg)
  sgMail.send(msg);
});

this throws an error:

UnhandledPromiseRejectionWarning: TypeError: sgMail.send is not a function at router.post

Upvotes: 0

Views: 639

Answers (2)

Samuel Goldenbaum
Samuel Goldenbaum

Reputation: 18909

I think you have the wrong module - you have@sendgrid/client which offers more than just sending mail, you should have @sendgrid/mail Node.js Library

Upvotes: 0

hoangdv
hoangdv

Reputation: 16127

Use @sendgrid/mail instead of @sendgrid/client. The @sendgrid/client package does not have .send function.

const sgMail = require('@sendgrid/mail'); instead of const sgMail = require('@sendgrid/client');

Upvotes: 1

Related Questions