微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

代码片段如下:

server/routes/passwordResetRoutes

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: "rawgrittt@gmail.com",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: "pgcim14.hemant@spjimr.org",html:
          "<p>Click on this <a href=`http://${req.headers.host}/password/reset/${user.passwordResetToken}`>link</a> to reset your password.</p>",};

enter image description here

解决方法

尝试添加

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

在 msg 对象的 html 属性中。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。