SendGrid是一个第三方的解决邮件发送服务的提供商,在国外使用的比较广泛。国内相似的服务是SendCloud.
SendGrid提供的发送邮件方式主要是两种, 一种是SMTP API, 一种是Web Api. SMTP API是一种比较简单的方式,只要咱们准备好Mail Message, 直接发送到SendGrid的邮件服务器就能够了,SendGrid的邮件服务器会帮咱们投递。另一种是Web Api的方式。git
通常来讲,不少三方的服务器提供商都会禁止连接外部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-webapigithub
代码中使用了RestSharp, 一个很是方便在.Net中使用的访问Restful API的工具包。一个完整的发送邮件的代码以下, 包含cc, bcc和附件。web
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 } }