.Net中使用SendGrid Web Api发送邮件(附源码)
2023-09-27 14:20:25 时间
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 } }
相关文章
- .NET Core首例Office开源跨平台组件(NPOI Core)
- ASP.NET MVC动态加载数据
- ASP.NET MVC一次删除多笔记录
- ASP.NET MVC实现权限控制
- ASP.NET MVC文章附加有源码下载的文章
- 在ASP.NET Core Web API 项目里无法访问(wwwroot)下的文件
- 通过.net core源码看下Dictionary的实现
- .NET 使用自带 DI 批量注入服务(Service)和 后台服务(BackgroundService)
- Orchard源码分析(7):ASP.NET MVC相关
- .NET(C#) SendKeys模拟键盘按键不生效使用WinAPI的替代方案
- ASP.NET Core应用的错误处理[4]:StatusCodePagesMiddleware中间件如何针对响应码呈现错误页面
- 集成EntLib实现ASP.NET MVC的异常处理
- QTVA-2015-198545、WooYun-2015-104148 .NET Framework Arbitrary File Permissions Modify Vul
- 自学MVC看这里——全网最全ASP.NET MVC 教程汇总(转)
- .net 6简单使用NPOI 读取 Excel 案例+流程