如何在sendgrid电子邮件正文中发送链接?

问题描述 投票:0回答:2

我正在 MERN 应用程序中实现密码重置功能。每当用户输入要重置密码的电子邮件并单击“发送密码链接”按钮时,就会向“/account/forgot”发出 POST 请求。在路由处理程序函数中,我想在通过 sendgrid 发送的电子邮件正文中向他们发送密码重置链接。我怎样才能实现这个目标?

代码片段如下:

服务器/路由/密码重置路由

const express = require("express");
const crypto = require("crypto");
const asyncHandler = require("express-async-handler");
const User = require("../models/userModel");

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


const router = express.Router();

router.post(
  "/forgot",
  asyncHandler(async (req, res, next) => {
    const user = await User.findOne({ email: req.body.email });

    if (user) {
      user.passwordResetToken = crypto.randomBytes(20).toString("hex");
      user.passwordResetExpires = Date.now() + 3600000;
      await user.save();

      res.json({
        message: "You have been emailed a password reset link",
      });

      // I WANT TO SEND THE passwordResetUrl in the email message
      const passwordResetUrl = `http://${req.headers.host}/password/reset/${user.passwordResetToken}`;

      const msg = {
        to: user.email,
        from: "[email protected]",
        subject: "PASSWORD RESET LINK",
        html:
          "<p>Click on the following link to reset your password.</p>",
      }
(async () => {
        try {
          await sgMail.send(msg);
        } catch (error) {
          console.error(error);

          if (error.response) {
            console.error(error.response.body);
          }
        }
      })();
    } else {
      const err = new Error("No account with that email exists");
      err.status = 404;
      next(err);
    }
  })
);

module.exports = router;

当我发送如下所示的邮件正文中的链接并单击该链接(在我的邮箱中收到)时,出现如下错误:

      const msg = {
        to: "[email protected]",
        from: "[email protected]",
        subject: "PASSWORD RESET LINK",
        html:
          "<p>Click on this <a href=`http://${req.headers.host}/password/reset/${user.passwordResetToken}`>link</a> to reset your password.</p>",
      };

node.js email sendgrid mern sendgrid-api-v3
2个回答
0
投票

尝试添加

<a href="resetPasswordLink">Click on the following link to reset your password</a>

在 msg 对象的 html 属性中。


0
投票

尝试更换这个

"<p>Click on this <a href=`http://${req.headers.host}/password/reset/${user.passwordResetToken}`>link</a> to reset your password.</p>"

这就是原因

`<p>Click on this <a href="http://${req.headers.host}/password/reset/${user.passwordResetToken}">link</a> to reset your password.</p>`

希望这有帮助

© www.soinside.com 2019 - 2024. All rights reserved.