使用C#的SendGrid V3 api无法发送邮件

时间:2016-06-20 10:20:21

标签: c# email sendgrid

这是我正在使用的代码。由于某种原因,它给出了一个错误:“未经授权”。任何想法为什么会这样。 Api密钥已正确配置。

String apiKey = Environment.GetEnvironmentVariable("SG.7cSY-INMQnCwIzmonlgZvA.zNtNDycx......", EnvironmentVariableTarget.User);
            dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://api.sendgrid.com");

            Email from = new Email("account@id.com");
            String subject = "Hello World from the SendGrid CSharp Library";
            Email to = new Email("someone@gmail.com");
            Content content = new Content("text/plain", "Textual content");
            Mail mail = new Mail(from, subject, to, content);
            //Email email = new Email("test2@example.com");
            //mail.Personalization[0].AddTo(email);

            String ret = mail.Get();

            string requestBody = ret;
            Console.WriteLine(ret);

            try
            {
                dynamic response = sg.client.mail.send.beta.post(requestBody: requestBody);
                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.Body.ReadAsStringAsync().Result);
                Console.WriteLine(response.Headers.ToString());
            }
            catch (Exception ex) {
                Console.WriteLine("SendGrid Error: {0}",ex.Message);
            }

1 个答案:

答案 0 :(得分:0)

在这行代码中:

String apiKey = Environment.GetEnvironmentVariable("SG.7cSY-INMQnCwIzmonlgZvA.zNtNDycx......", EnvironmentVariableTarget.User);

第一个参数是环境变量的名称,该变量包含您的SendGrid API密钥的值,其范围限定为用户的帐户。如果您没有使用环境变量,并且很乐意将API密钥放入代码中(不推荐,但这样可以测试它是否有效),您可以这样做:

String apiKey = "SG.7cSY-INMQnCwIzmonlgZvA.zNtNDycx......";