使用C#调用Twilio SendGrid v3 API获取退订列表的咨询
在C#中使用SendGrid v3 API获取退订列表的方案
一、使用SendGrid v3原生端点获取退订列表
SendGrid v3 API提供了专门的Suppressions接口管理退订记录,suppression/unsubscribes端点可直接获取全量退订列表。
你可以通过官方的Twilio.SendGrid NuGet包实现调用,示例代码如下:
using SendGrid; using SendGrid.Helpers.Suppressions; using System.Collections.Generic; using System.Threading.Tasks; public async Task<List<Unsubscribe>> FetchUnsubscribedRecipients(string sendGridApiKey) { var sendGridClient = new SendGridClient(sendGridApiKey); var apiResponse = await sendGridClient.RequestAsync( method: SendGridClient.Method.GET, urlPath: "suppression/unsubscribes" ); if (apiResponse.IsSuccessStatusCode) { return await apiResponse.DeserializeResponseBodyAsync<List<Unsubscribe>>(); } // 根据实际需求处理错误,比如抛出异常或返回空列表 return new List<Unsubscribe>(); }
获取到退订列表后,只需将列表中的邮箱地址与页面展示的收件人邮箱做匹配,即可为已退订用户添加标识。
二、调用SendGrid v2退订端点(不推荐)
官方的v3 SDK并未封装v2接口,如果确实需要调用v2的退订端点,需自行通过HTTP请求实现,示例代码如下:
using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Newtonsoft.Json; using System.Collections.Generic; using System; public async Task<List<dynamic>> FetchV2UnsubscribedRecipients(string sendGridApiKey) { using var httpClient = new HttpClient(); var authToken = Convert.ToBase64String(Encoding.ASCII.GetBytes($"apikey:{sendGridApiKey}")); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authToken); var response = await httpClient.GetAsync("https://api.sendgrid.com/v2/suppression/unsubscribes"); if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<List<dynamic>>(responseContent); } // 错误处理逻辑 return new List<dynamic>(); }
注意:SendGrid v2 API已被官方弃用,后续可能会停止服务,建议优先使用v3原生接口。
内容的提问来源于stack exchange,提问作者Takeo Nishioka
相关产品推荐
相关产品推荐

