Reputation: 544
Every time that I tried to send an E-mail I get the BadRequest related to a cross-origin. I've tried to search about the problem and it seems like because I'm calling from the browser (localhost) it wont work. Basically I'm making a Ajax call to my Aspnet mvc and them calling a WebApi project
public async Task<Response> SendEmail(string email, string link, string companyName)
{
var apiKey = Environment.GetEnvironmentVariable("SMTP");
var client = new SendGridClient(apiKey);
var from = new EmailAddress("d.com", "d");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress(email, "Caro");
var plainTextContent = "and easy to do anywhere, even with C#";
var htmlContent = "<strong>Aqui está seu contrato </strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
return await client.SendEmailAsync(msg);
}
That's the response :
{Server: nginx Date: Tue, 10 Dec 2019 14:17:40 GMT Connection: keep-alive Access-Control-Allow-Origin: https://sendgrid.api-docs.io Access-Control-Allow-Methods: POST Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl Access-Control-Max-Age: 600 X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html }
Not sure what to do anymore. Should I add something in the header at the HttpClient
Class ?
Upvotes: 1
Views: 456
Reputation: 467
private async Task<string> SendMail(string to, string text)
{
try
{
var msg = new SendGridMessage();
msg.SetFrom(new EmailAddress("[email protected]", "Your Name"));
msg.AddTo(to);
msg.SetSubject("Your subject here");
msg.AddContent(MimeType.Text, text);
var client = new SendGridClient("???"); // Your sendgrid client private id here
var response = await client.SendEmailAsync(msg);
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
return "ok";
else return "failed"; // not happening ))
}
catch (Exception e)
{
return e.Message;
}
}
Upvotes: 2