如何使用SendGrid在ExpressJS中发送电子邮件

时间:2019-11-17 22:22:44

标签: node.js express sendgrid-api-v3

我正在尝试关注https://sendgrid.com/docs/for-developers/sending-email/v3-nodejs-code-example/上的文档。作为测试,我试图在用户创建帖子时发送电子邮件。

这是我的代码:

在我的package.json中:

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

在posts.js路由中:

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: 'dariusgoore@gmail.com',
    from: 'team@writerboards.com',
    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);
});

这会引发错误:

  

UnhandledPromiseRejectionWarning:TypeError:sgMail.send不是   功能       在router.post

2 个答案:

答案 0 :(得分:1)

使用@sendgrid/mail代替@sendgrid/client@sendgrid/client软件包没有.send功能。

const sgMail = require('@sendgrid/mail');而不是const sgMail = require('@sendgrid/client');

答案 1 :(得分:0)

我认为您的模块有误-@sendgrid/client除了提供邮件发送功能外,还应该提供@sendgrid/mail Node.js Library