React unable to send email with SendGrid

廉价感情. 提交于 2020-03-05 03:21:52

问题


I am using react to send emails:

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);

But I got the following error:

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.

How do I fix it? Many thanks!


回答1:


Sendgrid won't let you send an email directly using Javascript in the browser.

You will need to have a server set-up and use the server to send the email instead (using your favourite back-end framework/language, Node.js, php, Java, etc.).

The steps for sending a mail will be similar to this:

  1. Write email details in the React application
  2. Send a POST request to your server endpoint (for example, /sendemail) with the email data (recipient, title, content, etc.)
  3. Receive Email data in the server and send it to Sendgrid api

Here is the official Sendgrid documentation regarding their CORS policy: https://sendgrid.com/docs/for-developers/sending-email/cors/



来源:https://stackoverflow.com/questions/54797626/react-unable-to-send-email-with-sendgrid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!