【问题标题】:asp.net Sendgrid Environment.GetEnvironmentVariable(APIKey) return null value / Permission denied, wrong credentialsasp.net Sendgrid Environment.GetEnvironmentVariable(APIKey) 返回空值/权限被拒绝,凭据错误
【发布时间】:2019-04-08 11:12:19
【问题描述】:

我有一个 asp.net (webforms) 应用程序,我正在使用 SendGrid 发送预定的电子邮件。

未收到电子邮件,当我检查 response.Body.ReadAsStringAsync().Result 时收到“权限被拒绝,凭据错误”

当我检查 Environment.GetEnvironmentVariable(APIKey) 的值时,它返回一个空值。

我从 webconfig 获取 SendGrid 键,它返回值。 我也试过直接在代码中添加 APIKey 字符串(SG...),我也遇到了同样的问题。

我认为我应该在某处添加 sendgrid 凭据,但在哪里?

我已经在使用此 ApiKey 从另一个应用程序发送电子邮件,并且它可以工作,但是我正在使用 smtpClient 发送这些电子邮件。

这是我正在使用的代码:

    private async Task TestSendEmail(DateTime SendAt)
    {
        string APIKey = ConfigurationManager.AppSettings["SendgridAPIKey"].ToString();

        var datetimeOffset = new DateTimeOffset(SendAt, TimeSpan.Zero);
        var apiKey = Environment.GetEnvironmentVariable(APIKey);
        var client = new SendGridClient(apiKey);
        //var from = new EmailAddress(QueueEmailAdmin, "Example User");
        var from = new EmailAddress("FromEmail@gmail.com");
        var subject = "Test Email";
        var to = new EmailAddress("myemail@gmail.com", "Example User");
        var plainTextContent = "This is a test";
        var htmlContent = "<strong>This is a test</strong>";
        var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
        msg.SendAt = datetimeOffset.ToUnixTimeSeconds();
        var response = await client.SendEmailAsync(msg).ConfigureAwait(false);
        Console.WriteLine(msg.Serialize());
        Console.WriteLine(response.StatusCode);
        Console.WriteLine(response.Body.ReadAsStringAsync().Result);
    }

【问题讨论】:

  • 我很困惑。您在 web.config 中没有值(API 密钥)吗?你期望 Environment.GetEnvironmentVariable() 做什么?您不应该将变量“APIKey”(在您的第一行)传递给 SendGridClient 的构造函数吗?
  • 是的,这就是我正在做的。但是,如果我查看值 var apiKey = Environment.GetEnvironmentVariable(APIKey);它返回一个空值。似乎它没有传递环境信息。我已经更新了帖子,因为我忘了提到没有收到电子邮件,我认为这是因为环境的值没有传递给变量 apiKey。
  • 我不认为 GetEnvironmentVariable() 正在做你认为它正在做的事情。它用于在您的计算机上全局设置环境变量。我假设您的 web.config 中有实际的 API 密钥,不是吗?在这种情况下,你应该忘记var apiKey = Environment.GetEnvironmentVariable(APIKey);这一行,并在var client = new SendGridClient(APIKey);的构造函数中使用string APIKey = ConfigurationManager.AppSettings["SendgridAPIKey"].ToString();的结果

标签: asp.net webforms sendgrid


【解决方案1】:

你必须这样写……

Environment.SetEnvironmentVariable("SENDGRID_API_KEY", APIKey);

var apikey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");

var client = new SendGridClient(apikey);

【讨论】:

    猜你喜欢
    • 2017-10-30
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多