简体   繁体   中英

Can't send Email with SendGrid and blazor webassembly

This is my code in blazor wasm application I get it from SendGrid document.

var toEmail = "portfolio1005@gmail.com";
var subject = "sub";
var body = "any body";
var apiKey = "apiKey";
var client = new SendGridClient(apiKey);
var FromFriendlyName = "From Name";
var FromEmailAddress = "portfolio1005@gmail.com";
var from = new EmailAddress(FromEmailAddress, FromFriendlyName);
var to = new EmailAddress(toEmail, toEmail);
var plainTextContent = body;
var htmlContent = body;
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg).ConfigureAwait(false);
return response.IsSuccessStatusCode;

When I run this code i get CORS Error

Access to fetch at 'https://api.sendgrid.com/v3/mail/send' from origin 'http://localhost:50855' 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.

I am tried to send Email with SendGrid, I expected to see the Email in my list but that does not husband

Browsers have built-in security that prevents website from sending HTTP requests to origins other than the origin you are currently on. An origin the unique combination of scheme, hostname, and port of the URL. The security feature preventing this is called Cross-Origin Resource Sharing (CORS).

The only way to allow this is for the origin that you're calling, to allow your origin to call its origin via CORS-headers. SendGrid does not allow you to configure this.

As mentioned in this SendGrid doc , you'd also expose your API key secret to the public which is very dangerous as anyone else could steal it and use it.

To achieve what you want to do, you first need to create a server-side application, since you're using Blazor, an ASP.NET Core Web API would make the most sense. In this server-side application, you can securely store the API key secret and make the API calls without the CORS restrictions, since it's not running inside the browser sandbox. From your client app, call your web API that takes care of communicating with the SendGrid API.

Note: you could use Blazor Hosted, Server, ASP.NET Core MVC, or ASP.NET Core Minimal APIs as your server-side portion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM