使用 sendgrid 发送电子邮件时在 Node.js 中禁止访问 403

403 Forbidden in Node.js while sending email using sendgrid

我正在设计一个联系人页面,其中 UI 使用 React 呈现。我有一个应该在提交时发送电子邮件的表格。这是处理提交的 UI 代码:

    handleSubmit = (event) => {
    event.preventDefault();

    this.setState({
        disabled: true
    });

    Axios.post('http://localhost:3040/api/email', this.state)
        .then( res => {
            if(res.data.success){

              this.setState({
                disabled: false,
                emailSent: true
              });
            } else{
                this.setState({
                    disabled: false,
                    emailSent: false
                });
            }
        })
        .catch(err => {
            this.setState({
                disabled: false,
                emailSent: false
            });
        });
}

发送邮件的api写在Node.js。使用@sendgrid//mail 来触发发送。在调试时我可以看到表单值达到 api 但在发送时它会抛出 403 Forbidden 错误。这是 api 代码:

app.post('/api/email', (req, res, next) => {
sendGrid.setApiKey('<Generated key in sendgrid>');
const msg = {
    to: 'some@email.com',
    from: req.body.email,
    subject: 'Website Contact Page',
    text: req.body.message
}

sendGrid.send(msg).then(result => {
    res.status(200).json({
        success: true
    });
})
.catch(err => {
    console.log('error: ', err);
    res.status(401).json({
        success: false
    });
});
});

以下是我在调试时在 VSCode 控制台中得到的错误跟踪:

stack:"Error: Forbidden
at axios.then.catch.error (c:\react\portfolio-api\node_modules\@sendgrid\client\src\classes\client.js:105:29)
at process._tickCallback (internal/process/next_tick.js:68:7)"

proto:错误{构造函数:,toString:,toJSON:}

不知道为什么它给我禁止错误。如果我需要在此处添加更多信息,请告诉我。提前致谢:)

编辑:- 按照 sendgrid 上的文档创建一个 API 密钥并在 sendGrid.setApiKey().

中使用相同的密钥

为了能够从 sendgrid 发送电子邮件,您需要设置单一发件人验证或域验证。

请检查docs以验证发件人。

To ensure our customers maintain the best possible sender reputations and to uphold legitimate sending behavior, we require customers to verify their Sender Identities. A Sender Identity represents your “From” email address—the address your recipients will see as the sender of your emails.

You can verify one or more Sender Identities using either Domain Authentication or Single Sender Verification.

在您的 api 应用程序控制台日志中,错误消息必须如下所示: (要在reactjs端看到真正的错误信息,需要使用err.response.data.

The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved.