![](/img/trans.png)
[英]Sending an email with SendGrid API from ASP.Net Framework 3.5
[英]SendGrid Web API in ASP.NET 3.5
我正在使用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();
您的主要問題是您向我們發送了帶有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);
}
}
}
@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; }
}
CONTROLLER
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";
}
使用以下網址找到的c#代碼庫: https : //github.com/sendgrid/sendgrid-csharp
//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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.