SendGrid是一個第三方的解決郵件發送服務的提供商,在國外使用的比較普遍。國內類似的服務是SendCloud.
SendGrid提供的發送郵件方式主要是兩種, 一種是SMTP API, 一種是Web Api. SMTP API是一種比較簡單的方式,只要我們准備好Mail Message, 直接發送到SendGrid的郵件服務器就可以了,SendGrid的郵件服務器會幫我們投遞。另外一種是Web Api的方式。
一般來說,很多三方的服務器提供商都會禁止鏈接外部25端口,這樣你就沒有辦法連接SendGrid的SMTP服務器發送郵件了。在這種情況下,Web API就是一個很好的選擇。SengGrid官方有較為詳細的SMTP API Demo. Demo的地址是 https://github.com/sendgrid/sendgrid-csharp 由於沒有Web API的Demo, 自己花時間自己寫了一份,現在共享出來https://github.com/justrun1983/sendgrid-csharp-webapi
代碼中使用了RestSharp, 一個非常方便在.Net中使用的訪問Restful API的工具包。一個完整的發送郵件的代碼如下, 包含cc, bcc和附件。
public class WebApiRestSharp { private const string ApiWebSite = "https://sendgrid.com"; private const string ApiUrlAddress = "api/mail.send.json"; public static void SendNormalHelloWorldEmail() { var client = new RestClient(ApiWebSite); var request = new RestRequest(ApiUrlAddress, Method.POST); request.AddParameter("api_user", Config.SendGridName); request.AddParameter("api_key", Config.SendGridPassword); request.AddParameter("to[]", Config.ToEmail); request.AddParameter("cc[]", Config.ToEmail); request.AddParameter("bcc[]", Config.ToEmail); request.AddParameter("subject", "Test"); request.AddParameter("from", "test@test.me"); request.AddParameter("text", "HelloWorld1"); request.AddFile("files[2.txt]", @"C:\1.txt"); // execute the request var response = client.Execute(request); var content = response.Content; // raw content as string } }