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

How to use SendGrid to send email in ExpressJS

我正在尝试按照 https://sendgrid.com/docs/for-developers/sending-email/v3-nodejs-code-example/ 上的文档进行操作。作为测试,我尝试在用户创建 post.

时发送电子邮件

这是我的代码:

在我的 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 is not a function at router.post

使用 @sendgrid/mail 而不是 @sendgrid/client@sendgrid/client 包没有 .send 功能。

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

我认为你有错误的模块 - 你有 @sendgrid/client 它提供的不仅仅是发送邮件,你应该有 @sendgrid/mail Node.js Library