首页 > 解决方案 > 使用 Sendgrid/mail 和 nodejs 防止未处理的承诺拒绝

问题描述

我根本没有收到我的电子邮件,并且我在 processTicksAndRejections 的终端中收到错误消息。我不确定我是否必须在我的函数中添加一个异步来处理错误。我还尝试清除我的 npm 缓存,但我的错误没有任何变化。我的电子邮件被拒绝了,我附加了云,当我上传时我可以在云仪表板中看到我的图像,但我没有收到发送到我的电子邮件的图像和表格的电子邮件。

控制器/反馈.js

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

exports.emailFeedback = (req, res) => {
  // console.log(req.body);
  const { name, email, message, phone, uploadedFiles } = req.body;
  const emailData = {
    to: process.env.EMAIL_TO,
    from: email,
    subject: "Feedback form",
    html: `
            <h1>Customer Feedback Form</h1>
            <hr />
            <h2>Sender name: ${name}</h2>
            <h2>Sender email: ${email}</h2>
            <h2>Sender message: ${message}</h2>
            <br />
            ${uploadedFiles.map((f) => {
              return `<img src="${f.secure_url}" alt="${f.original_filename}" style="width:50%;overflow:hidden;padding:50px;" />`;
            })}
            <hr />
            <p>https://feedbackonline.com</p>
        `,
  };

  sgMail
    .send(emailData)
    .then((sent) => {
      console.log(sent);
      return res.json({
        success: true,
      });
    })
    .catch((err) => {
      console.log(err);
      return res.json({
        success: false,
      });
    });
};

当我将呼叫从 get 更改为 post 时,我在无法 GET /api 的 localhost 中收到错误。

标签: node.jsreactjssendgrid

解决方案


我通过添加我要发送回复的电子邮件地址来创建电子邮件发件人验证,从而解决了这个问题。

// 这个测试有效

const sgMail = require("@sendgrid/mail");

const API_KEY =
  "";

sgMail.setApiKey(API_KEY);

const message = {
  to: "zilahmusicpub@outlook.com",
  from: "tailoredr@mail.com",
  subject: "Hello from sendgrid",
  text: "Hello from sendgrid",
  html: "<h1>Hello from sendgrid to outlook</h1>",
};

sgMail
  .send(message)
  .then((response) => console.log("Email sent..."))
  .catch((error) => console.log(error.message));

推荐阅读