2016-06-20 50 views
0

這是我正在使用的代碼。出於某種原因,它給出了一個錯誤:'未經授權'。任何想法,爲什麼這可能會發生。 Api鍵已正確配置。SendGrid V3 api與C#無法發送郵件

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

      Email from = new Email("[email protected]"); 
      String subject = "Hello World from the SendGrid CSharp Library"; 
      Email to = new Email("[email protected]"); 
      Content content = new Content("text/plain", "Textual content"); 
      Mail mail = new Mail(from, subject, to, content); 
      //Email email = new Email("[email protected]"); 
      //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); 
      } 

回答

0

在這行代碼:

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

的第一個參數是握着你的SendGrid API密鑰值的環境變量的名稱,範圍的用戶的帳戶。如果你不使用環境變量,是舒適的把你的API密鑰在你的代碼(不推薦,但是這將讓你測試,它的作品),你會做:

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

好了,如果我指正我錯了:'EnvironmentVariable'和'AppSettings'非常相似。但是,通過'EnvironmentVariable',您可以爲不同的用戶存儲不同的API-Key(不同的配置)。 –

+1

我對AppSettings不熟悉。對於EnvironmentVariable,我的理解是,您可以從當前用戶空間或系統範圍獲取值。在上面的代碼中,我假設你在用戶空間中設置了環境變量。 –