2012-07-24 52 views
4

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

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

回答

11

你的主要问题是,你向我们发送了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 = "[email protected]"; 
    string toName = "To Name"; 
    string subject = "A message from SendGrid"; 
    string text = "Delivered by your friends at SendGrid."; 
    string fromAddress = "[email protected]"; 

    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); 
    } 
    } 
} 
+0

嗨感谢响应,这是修改 “的ContentType” 之后现在的工作和参数编码。我还有一个问题“如何发送附件像TXT,PDF ......”提前致谢。 – user1547639 2012-07-25 07:06:41

+1

@Swift我在使用你的代码后得到错误“不良请求(400)”......可能是什么原因? – Steve 2016-07-12 11:19:28

+0

如何附加文件? – 2016-10-20 05:47:59

-1

在使用中发现的C#-code库:https://github.com/sendgrid/sendgrid-csharp

//Create message 
SendGrid myMessage = SendGrid.GetInstance(); 
myMessage.AddTo("[email protected]"); 
myMessage.From = new MailAddress("[email protected]", "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); 
+0

尽管这个链接可能回答这个问题,但最好在这里包含答案的基本部分,并提供参考链接。如果链接页面更改,则仅链接答案可能会失效。 – stema 2014-04-30 11:36:47

+0

@stema用编码编辑。 – cederlof 2014-04-30 12:10:11

+0

@cederlof你有C#中的Sendgrid完整的工作代码吗? – Steve 2016-07-12 11:20:29

0

通过@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 = "[email protected]"; 
     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"; 
    }