代码改变世界

.Net中使用SendGrid Web Api发送邮件(附源码)

  JustRun  阅读(4694)  评论(7编辑  收藏  举报

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
      }
  }
复制代码

 

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示