如何在NodeJS中通过电子邮件接收器参数传递带有发送网格服务的发送电子邮件功能

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

我现在向我的NodeJS API添加了一个端点来发送电子邮件,这是一个简单的功能,可以发送经过硬编码的电子邮件,而我是使用Send Grid服务来完成的。我现在想要实现的是,我可以在端点请求中传递收件人电子邮件并发送电子邮件。端点url/email/:email的示例:email将成为电子邮件的收件人。我想将此参数传递给我的电子邮件功能,该功能将在那里发送。但由于无法理解如何将参数传递到sen电子邮件中,所以我将其堆叠起来,就像现在是我的代码一样。

到目前为止我尝试过的:

路由器

// POST email send
router.post("/email/:email", async (req, res) => {
    const email = req.params.email;
    try {
        const sent = await sendEmail(email);
        if (sent) {
            res.send({ message: "email sent successfully", status: 200 });
            console.log("Email sent");
        }
    } catch (error) {
        throw new Error(error.message);
    }
});

// Routes
module.exports = router;

发送电子邮件

const mailGenerator = new MailGen({
    theme: "salted",
    product: {
        name: "Awesome Movies",
        link: "http://example.com"
    }
});

const email = {
    body: {
        name: receiver here??,
        intro: "Welcome to the movie platform",
        action: {
            instructions:
                "Please click the button below to checkout new movies",
            button: {
                color: "#33b5e5",
                text: "New Movies Waiting For you",
                link: "http://example.com/"
            }
        }
    }
};

const emailTemplate = mailGenerator.generate(email);
require("fs").writeFileSync("preview.html", emailTemplate, "utf8");

const msg = {
    to: receiver here??,
    from: "[email protected]",
    subject: "Testing email from NodeJS",
    html: emailTemplate
};

const sendEmail = () => {
    try {
        sgMail.setApiKey(sg_token);
        return sgMail.send(msg);
    } catch (error) {
        throw new Error(error.message);
    }
};

module.exports = { sendEmail };
node.js email sendgrid
1个回答
0
投票

您的sendEmail方法不接受参数。在签名上添加接收者并使用它

const sendEmail = (receiver) => {
    try {
        sgMail.setApiKey(sg_token);
        return sgMail.send({ ...msg, to: receiver });
    } catch (error) {
        throw new Error(error.message);
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.