【问题标题】:How to send a link in the sendgrid email message body?如何在 sendgrid 电子邮件正文中发送链接?
【发布时间】:2021-06-19 22:53:53
【问题描述】:

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

代码sn-p如下:

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

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",
        from: "rawgrittt@gmail.com",
        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>",
      };

【问题讨论】:

  • 您不能正常发送&lt;p&gt;&lt;a href="_LINK_HERE_"&gt;Click to reset your password.&lt;/a&gt;&lt;/p&gt;
  • 不,我收到错误消息。请查看我的问题中的编辑。
  • 我在发送带有有效链接的电子邮件时没有问题... -> screenshot
  • repository with code 如果你需要它运行
  • 谢谢。现在问题解决了。

标签: node.js email sendgrid mern sendgrid-api-v3


【解决方案1】:

尝试添加

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

在 msg 对象的 html 属性中。

【讨论】:

  • 请添加代码 sn-p 而不是链接,因为该链接最终可能是恶意的,人们根本不会查看它。您可以在 StackOverflow 答案中轻松添加代码 sn-ps。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-30
相关资源
最近更新 更多