【问题标题】:SendGrid Web API in ASP.NET 3.5ASP.NET 3.5 中的 SendGrid Web API
【发布时间】:2012-07-24 05:35:07
【问题描述】:

我正在使用 SendGrid 电子邮件服务通过 Web API (HttpWebRequest) 发送电子邮件。这是正在使用的代码,但我收到了 400 响应。

string url = "https://sendgrid.com/api/mail.send.xml";
string parameters = "api_user=" + api_user + "&api_key=" + api_key + "&to="                     + toAddress + "&toname=" + toName + "&subject=" + subject + "&text=" + text + "&from=" + fromAddress;

// Create Request
myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);

myHttpWebRequest.Method = "POST";
// myHttpWebRequest.ContentType = "application/json; charset=utf-8";
myHttpWebRequest.ContentType = "text/xml";

CookieContainer cc = new CookieContainer();
myHttpWebRequest.CookieContainer = cc;

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] postByteArray = encoding.GetBytes(parameters);
myHttpWebRequest.ContentLength = postByteArray.Length;
System.IO.Stream postStream = myHttpWebRequest.GetRequestStream();
postStream.Write(postByteArray, 0, postByteArray.Length);
postStream.Close();

// Get Response
string result="";
HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();

【问题讨论】:

    标签: c# asp.net sendgrid


    【解决方案1】:

    您的主要问题是您向我们发送的内容类型为 text/xml,但我们只接受表单编码的内容或查询字符串。这是您尝试执行的操作的完整示例。

    using System;
    using System.IO;
    using System.Net;
    
    public class SendGridWebDemo
    {
      static public void Main ()
      {
        string api_user = "your_sendgrid_username";
        string api_key = "your_sendgrid_key";
        string toAddress = "to@example.com";
        string toName = "To Name";
        string subject = "A message from SendGrid";
        string text = "Delivered by your friends at SendGrid.";
        string fromAddress = "from@example.com";
    
        string url = "https://sendgrid.com/api/mail.send.json";
    
        // Create a form encoded string for the request body
        string parameters = "api_user=" + api_user + "&api_key=" + api_key + "&to=" + toAddress + 
                            "&toname=" + toName + "&subject=" + subject + "&text=" + text + 
                            "&from=" + fromAddress;
    
        try
        {
          //Create Request
          HttpWebRequest myHttpWebRequest = (HttpWebRequest) HttpWebRequest.Create(url);
          myHttpWebRequest.Method = "POST";
          myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
    
          // Create a new write stream for the POST body
          StreamWriter streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream());
    
          // Write the parameters to the stream
          streamWriter.Write(parameters);
          streamWriter.Flush();
          streamWriter.Close();
    
          // Get the response
          HttpWebResponse httpResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
    
          // Create a new read stream for the response body and read it
          StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream());
          string result = streamReader.ReadToEnd();
    
          // Write the results to the console
          Console.WriteLine(result);
        }
        catch(WebException ex)
        {
          // Catch any execptions and gather the response
          HttpWebResponse response = (HttpWebResponse) ex.Response;
    
          // Create a new read stream for the exception body and read it
          StreamReader streamReader = new StreamReader(response.GetResponseStream());
          string result = streamReader.ReadToEnd();
    
          // Write the results to the console
          Console.WriteLine(result);
        }
      }
    }
    

    【讨论】:

    • 您好,感谢您的回复,在修改“ContentType”和编码的参数后,它现在可以工作了。我还有一个问题“如何发送 txt、PDF 等附件...”提前致谢。
    • @Swift 我在使用您的代码后收到错误“bad request(400)”...可能是什么原因?
    • 如何附加文件??
    【解决方案2】:

    @Swift 的回答是正确的。这是我使用 MVC Web 表单的答案。替换console.writeline等

    <div class="form">
         <input class="input-text" type="text" id="RecipientName" name="RecipientName" value="Your Name *" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">
         <input class="input-text" type="text" id="RecipientEmail" name="RecipientEmail" value="Your E-mail *" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">
         <textarea class="input-text text-area" id="RecipientMessage" name="RecipientMessage" cols="0" rows="0" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">Your Message *</textarea>
         <input class="input-btn" type="submit" id="EmailSendButton" name="EmailSendButton" value="send message" onclick="EmailData()">
         <div id="EmailConfirmation"></div>
    </div>
    
    
    <script>
        function EmailData() {
            $("#EmailSendButton").attr("disabled", "true");
    
            var url = "/Main/EmailData";
            var recipientName = $("#RecipientName").val();
            var recipientEmail = $("#RecipientEmail").val();
            var recipientMessage = $("#RecipientMessage").val();
            var postData = { 'Name': recipientName, 'Email': recipientEmail, 'Message': recipientMessage }
            $.post(url, postData, function (result) {
                $("#EmailConfirmation").css({ 'display': 'block' });
                $("#EmailConfirmation").text(result);
                $("#EmailConfirmation").fadeIn(2000)
            })
        }
    </script>
    

    视图模型

    public class EmailDataViewModel
    {
        public string Name { get; set; }
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }
        public string Message { get; set; }
    }
    

    控制器

    public string EmailData(EmailDataViewModel viewModel)
        {
            string api_user = "username";
            string api_key = "password";
            string toAddress = "admin@webapp.com";
            string toName = "Administrator";
            string subject = "Message from your web app";
            string text = viewModel.Name + " " + viewModel.Message;
            string fromAddress = viewModel.Email;
            string url = "https://sendgrid.com/api/mail.send.json";
            // Create a form encoded string for the request body
            string parameters = "api_user=" + api_user + "&api_key=" + api_key + "&to=" + toAddress +
                                "&toname=" + toName + "&subject=" + subject + "&text=" + text +
                                "&from=" + fromAddress;
    
            try
            {
                //Create Request
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                myHttpWebRequest.Method = "POST";
                myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
    
                // Create a new write stream for the POST body
                StreamWriter streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream());
    
                // Write the parameters to the stream
                streamWriter.Write(parameters);
                streamWriter.Flush();
                streamWriter.Close();
    
                // Get the response
                HttpWebResponse httpResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
    
                // Create a new read stream for the response body and read it
                StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream());
                string result = streamReader.ReadToEnd();
    
                // Write the results to the console
                Console.WriteLine(result);
            }
            catch (WebException ex)
            {
                // Catch any execptions and gather the response
                HttpWebResponse response = (HttpWebResponse)ex.Response;
    
                // Create a new read stream for the exception body and read it
                StreamReader streamReader = new StreamReader(response.GetResponseStream());
                string result = streamReader.ReadToEnd();
    
                // Write the results to the console
                Console.WriteLine(result);
            }
    
            return "Successful";
        }
    

    【讨论】:

      【解决方案3】:

      使用位于 https://github.com/sendgrid/sendgrid-csharp 的 c# 代码库

      //Create message
      SendGrid myMessage = SendGrid.GetInstance();
      myMessage.AddTo("anna@example.com");
      myMessage.From = new MailAddress("john@example.com", "John Smith");
      myMessage.Subject = "Testing the SendGrid Library";
      myMessage.Text = "Hello World!";
      
      // Add attachment
      myMessage.AddAttachment(@"C:\file1.txt");
      
      //Set up the transport
      var credentials = new NetworkCredential("username", "password");
      var transportWeb = Web.GetInstance(credentials);
      
      // Send the email.
      transportWeb.Deliver(myMessage);
      

      【讨论】:

      • @cederlof 你有 C# 中 Sendgrid 的完整工作代码吗?
      • @Steve 对不起,不是手头的,上面的代码不适合你吗?
      • @cederlof 以上代码正在运行,但我想使用 Sendgid API 而不是提供用户名和密码
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多