React无法使用SendGrid发送电子邮件

时间:2019-02-21 00:58:33

标签: reactjs sendgrid

我正在使用React发送电子邮件:

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.REACT_APP_SENDGRID);
const msg = {
  to: 'test@example.com',
  from: 'test@example.com',
  subject: 'Sending with SendGrid is Fun',
  text: 'and easy to do anywhere, even with Node.js',
  html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);

但是我遇到了以下错误:

Access to fetch at 'https://api.sendgrid.com/v3/mail/send' 
from origin 'http://localhost:3000' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
The 'Access-Control-Allow-Origin' header has a value 'https://sendgrid.api-docs.io' that is not equal to the supplied origin. 
Have the server send the header with a valid value, or, if an opaque response serves your needs, 
set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我该如何解决?非常感谢!

1 个答案:

答案 0 :(得分:3)

Sendgrid不允许您使用浏览器中的Javascript直接发送电子邮件。

您将需要设置服务器并使用该服务器发送电子邮件(使用您喜欢的后端框架/语言,Node.js,php,Java等)。

发送邮件的步骤与此类似:

  1. 在React应用程序中写电子邮件详细信息
  2. 将POST请求和电子邮件数据(收件人,标题,内容等)发送到服务器端点(例如,/ sendemail)
  3. 在服务器中接收电子邮件数据并将其发送到Sendgrid api

以下是有关其CORS政策的官方 Sendgrid 文档:https://sendgrid.com/docs/for-developers/sending-email/cors/

相关问题