如何在sendgrid电子邮件正文中发送链接? [英] How to send a link in the sendgrid email message body?

查看:76
本文介绍了如何在sendgrid电子邮件正文中发送链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在MERN应用程序中实现密码重置功能.每当用户输入要为其重设密码的电子邮件并单击发送密码链接"时,都会在该电子邮件中单击发送密码链接".按钮,向"/帐户/忘记"发出POST请求.在路由处理程序功能中,我想在通过sendgrid发送的电子邮件正文中向他们发送一个密码重置链接.我该如何实现?

I am implementing password reset functionality in a MERN app. Whenever a user enters the email for which they want to reset the password and clicks on the "Send Password Link" button, a POST request is made to "/account/forgot". In the route handler function, I want to send them a password reset link in the body of the email message sent through sendgrid. How can I achieve this?

代码段如下:

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

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;

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

When I send the link in the message body as shown below and click on the link (received in my mailbox), I get an error as follows:

      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>",
      };

推荐答案

尝试添加

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

在msg对象的html属性中.

in html property of msg object.

这篇关于如何在sendgrid电子邮件正文中发送链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆