无法使用SendGrid WebApi lib发送电子邮件

时间:2019-12-10 14:11:30

标签: c# sendgrid

每次尝试发送电子邮件时,都会收到与跨域相关的BadRequest。我试图搜索问题,但似乎是因为我是从浏览器(本地主机)调用,因此无法正常工作。 基本上,我正在对我的Aspnet mvc进行Ajax调用,他们调用了WebApi项目

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

    }

这是响应:

  

{服务器:nginx   日期:2019年12月10日,星期二14:17:40 GMT   连接:保持活动状态   访问控制允许来源:https://sendgrid.api-docs.io   访问控制允许方法:POST   访问控制允许标头:授权,内容类型,代表,x-sg-elas-acl   存取控制的最大年龄:600   X-否-CORS原因:https://sendgrid.com/docs/Classroom/Basics/API/cors.html   }

不知道该怎么办。我应该在HttpClient类的标题中添加一些内容吗?

1 个答案:

答案 0 :(得分:2)

 private async Task<string> SendMail(string to, string text)
        {
            try
            {
                var msg = new SendGridMessage();
                msg.SetFrom(new EmailAddress("youremail@email.com", "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;
            }
        }