首页
/ Twilio SendGrid C .NET 库技术文档

Twilio SendGrid C .NET 库技术文档

2024-12-28 04:14:36作者:段琳惟

1. 安装指南

准备条件

  • .NET Framework 4.0+
  • .NET Core 1.0+
  • .NET Standard 1.3+
  • Twilio SendGrid 账户,免费注册可在前30天内发送最多40,000封邮件,之后每天可免费发送100封邮件或查看我们的定价

获取 API Key

Twilio SendGrid UI 获取您的 API Key。

设置环境变量以管理 API Key

通过环境变量或 Web.config 来管理您的 Twilio SendGrid API Key,这是一个好习惯,可以将数据配置设置与代码分离。这样,您可以在不更改代码的情况下更改 Twilio SendGrid API Key。

使用 UI 设置环境变量:

  1. 按下 Win+R 并运行 SystemPropertiesAdvanced
  2. 点击环境变量
  3. 在用户变量部分点击新建
  4. 在名称中输入 SENDGRID_API_KEY(确保名称与代码中的键名称匹配)
  5. 在值中输入实际的 API Key
  6. 重启 IDE,完成设置

使用 CMD 设置环境变量:

  1. 以管理员身份运行 CMD
  2. 运行 set SENDGRID_API_KEY="YOUR_API_KEY"

以下是一些以编程方式获取和设置 API Key 的示例:

// 获取环境变量
var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");

// 设置环境变量
var setKey = Environment.SetEnvironmentVariable("SENDGRID_API_KEY", "YOUR_API_KEY");

安装包

要在您的 C# 项目中使用 Twilio SendGrid,您可以直接从我们的 GitHub 仓库 下载 Twilio SendGrid C# .NET 库,或者如果您已安装 NuGet 包管理器,可以自动获取:

dotnet add package SendGrid

# 使用 HttpClientFactory 和 Microsoft.Extensions.DependencyInjection
dotnet add package SendGrid.Extensions.DependencyInjection

安装完 Twilio SendGrid 库后,您可以在代码中调用它。有关示例实现,请参阅 .NET Core 示例.NET 4.5.2 示例 文件夹。

依赖项

请查看 .csproj 文件 中的依赖项。

2. 项目使用说明

快速入门

以下是最小代码示例,用于发送简单邮件。请使用此示例,并修改 apiKeyfromto 变量:

using System;
using System.Threading.Tasks;
using SendGrid;
using SendGrid.Helpers.Mail;

class Program
{
    static async Task Main()
    {
        var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
        var client = new SendGridClient(apiKey);
        var from = new EmailAddress("test@example.com", "Example User");
        var subject = "Sending with Twilio SendGrid is Fun";
        var to = new EmailAddress("test@example.com", "Example User");
        var plainTextContent = "and easy to do anywhere, even with C#";
        var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
        var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
        var response = await client.SendEmailAsync(msg).ConfigureAwait(false);
    }
}

执行上述代码后,response.StatusCode 应该为 202,并且您应该在 to 收件人的收件箱中收到一封邮件。您可以在 UI 中查看邮件状态。或者,我们可以将事件发布到您选择的 URL,使用我们的 事件 Webhook。这将为您提供 Twilio SendGrid 处理邮件时的有关事件数据。

对于更高级的情况,您可以自己构建 SendGridMessage 对象,至少需要以下设置:

using System;
using System.Threading.Tasks;
using SendGrid;
using SendGrid.Helpers.Mail;

class Program
{
    static async Task Main()
    {
        var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
        var client = new SendGridClient(apiKey);
        var msg = new SendGridMessage()
        {
            From = new EmailAddress("test@example.com", "DX Team"),
            Subject = "Sending with Twilio SendGrid is Fun",
            PlainTextContent = "and easy to do anywhere, even with C#",
            HtmlContent = "<strong>and easy to do anywhere, even with C#</strong>"
        };
        msg.AddTo(new EmailAddress("test@example.com", "Test User"));
        var response = await client.SendEmailAsync(msg).ConfigureAwait(false);
    }
}

您可以在此处找到所有邮件功能的示例。

通用 v3 Web API 使用

using System;
using System.Threading.Tasks;
using SendGrid;

class Program
{
    static async Task Main()
    {
        var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
        var client = new SendGridClient(apiKey);
        var queryParams = @"{'limit': 100}";
        var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/bounces", queryParams: queryParams).ConfigureAwait(false);
    }
}

HttpClientFactory + Microsoft.Extensions.DependencyInjection

需要安装 SendGrid.Extensions.DependencyInjection

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using SendGrid;
using SendGrid.Extensions.DependencyInjection;
using SendGrid.Helpers.Mail;

class Program
{
    static async Task Main()
    {
        var services = ConfigureServices(new ServiceCollection()).BuildServiceProvider();
        var client = services.GetRequiredService<ISendGridClient>();
        var msg = new SendGridMessage()
        {
            From = new EmailAddress("test@example.com", "Example User"),
            Subject = "Sending with Twilio SendGrid is Fun"
        };
        msg.AddContent(MimeType.Text, "and easy to do anywhere, even with C#");
        msg.AddTo(new EmailAddress("test@example.com", "Example User"));
        var response = await client.SendEmailAsync(msg).ConfigureAwait(false);
    }

    private static IServiceCollection ConfigureServices(IServiceCollection services)
    {
        services.AddSendGrid(options =>
        {
            options.ApiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
        });

        return services;
    }
}

Web 代理

var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
var proxy = new WebProxy("http://proxy:1337");
var client = new SendGridClient(proxy, apiKey);

或者在使用 DependencyInjection 时:

services.AddSendGrid(options =>
{
    options.ApiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
})
.ConfigurePrimaryHttpMessageHandler(_ => new HttpClientHandler()
{
    Proxy = new WebProxy(new Uri("http://proxy:1337")),
    UseProxy = true
});

3. 项目 API 使用文档

请参考以下文档以获取关于 Twilio SendGrid API 的详细信息:

4. 项目安装方式

请按照以下步骤安装 Twilio SendGrid C# .NET 库:

  1. 通过 NuGet 包管理器自动获取:
dotnet add package SendGrid
  1. 使用 HttpClientFactory 和 Microsoft.Extensions.DependencyInjection:
dotnet add package SendGrid.Extensions.DependencyInjection
  1. GitHub 仓库 下载库文件。

  2. 将库文件添加到您的 C# 项目中,并根据需要调用相关功能。

登录后查看全文
热门项目推荐

热门内容推荐

最新内容推荐

项目优选

收起
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
176
261
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
858
509
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
129
182
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
257
300
ShopXO开源商城ShopXO开源商城
🔥🔥🔥ShopXO企业级免费开源商城系统,可视化DIY拖拽装修、包含PC、H5、多端小程序(微信+支付宝+百度+头条&抖音+QQ+快手)、APP、多仓库、多商户、多门店、IM客服、进销存,遵循MIT开源协议发布、基于ThinkPHP8框架研发
JavaScript
93
15
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
331
1.08 K
HarmonyOS-ExamplesHarmonyOS-Examples
本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计!
Cangjie
397
370
note-gennote-gen
一款跨平台的 Markdown AI 笔记软件,致力于使用 AI 建立记录和写作的桥梁。
TSX
83
4
CangjieCommunityCangjieCommunity
为仓颉编程语言开发者打造活跃、开放、高质量的社区环境
Markdown
1.07 K
0
kernelkernel
deepin linux kernel
C
22
5