Sendgrid 取消订阅首选项

问题描述 投票:0回答:2

我正在使用 Sendgrid 并尝试使用 C# 语言发送这些电子邮件。 所以,我正在做的是在我的应用程序中配置 SMTP 和 API 密钥,然后,邮件就发送了。

问题是,如何在我的 X-SMTPAPI 标头中插入 Unsubscribe Preferences 组? 仅供参考,取消订阅首选项是您可以选择要取消订阅的组而不是全局取消订阅的地方。

我已经检查过这些链接:

我还在他们的 github 上检查了 C# 库。 但这些都没有让我清楚。

我对 JSON、GET、REQUEST、RESPONSE 等完全盲目。

这是我的 C# 代码

        public void Main()
                {
                    string sSubject = Dts.Variables["vSubject"].Value.ToString();
                    string sBody = Dts.Variables["vBodyMessage"].Value.ToString();

                    int iPriority = 2;



                    if (SendMail(sSubject, sBody, iPriority))
                    {
                        Dts.TaskResult = (int)ScriptResults.Success;
                    }
                    else
                    {
                        //Fails the Task
                        Dts.TaskResult = (int)ScriptResults.Failure;
                    }
                }

//THIS IS THE HEADER X-SMTPAPI, I DUNNO HOW TO USE IT :(
//I WANNA ADD MY GROUPS HERE
    private static string XsmtpapiHeaderAsJson()
            {
                var header = new Header();
                header.SetAsmGroupId(777);

                //var uniqueArgs = new string[] { "Small", "Medium", "Large" };
                //{

                //      "asm_groups_to_display": [1, 2, 3]

                //};
                //header.AddUniqueArgs({ "asm_groups_to_display": ['1', '2', '3']});

                //var subs = new List<String> { "私はラーメンが大好き" };
                //header.AddSubstitution("%tag%", subs);

                //dynamic stuff = json

                return header.JsonString();
            }

    public bool SendMail(string sSubject, string sMessage, int iPriority)
            {
                string xmstpapiJson = XsmtpapiHeaderAsJson();

                try
                {
                    string sEmailServer = Dts.Variables["sServer"].Value.ToString();
                    string sEmailPort = Dts.Variables["sPort"].Value.ToString();
                    string sEmailUser = Dts.Variables["sUser"].Value.ToString();
                    string sEmailPassword = Dts.Variables["sPassword"].Value.ToString();
                    string sEmailSendTo = Dts.Variables["sSendTo"].Value.ToString();
                    string sEmailSendToName = Dts.Variables["sSendToName"].Value.ToString();
                    //string sEmailSendCC = Dts.Variables["sSendCC"].Value.ToString();
                    string sEmailSendFrom = Dts.Variables["sFrom"].Value.ToString();
                    string sEmailSendFromName = Dts.Variables["sFromName"].Value.ToString();

                    SmtpClient smtpClient = new SmtpClient();
                    MailMessage message = new MailMessage();

                    MailAddress fromAddress = new MailAddress(sEmailSendFrom, sEmailSendFromName);

                    //You can have multiple emails separated by ;
                    string[] sEmailTo = Regex.Split(sEmailSendTo, ";");
                    //string[] sEmailCC = Regex.Split(sEmailSendCC, ";");
                    int sEmailServerSMTP = int.Parse(sEmailPort);

                    smtpClient.Host = sEmailServer;
                    smtpClient.Port = sEmailServerSMTP;

                    System.Net.NetworkCredential myCredentials =
                       new System.Net.NetworkCredential(sEmailUser, sEmailPassword);
                    smtpClient.Credentials = myCredentials;

                    message.From = fromAddress;

                    //MailAddress toAddress = new MailAddress(sEmailSendTo, sEmailSendToName);
                    //message.To.Add(toAddress);

                    if (sEmailTo != null)
                    {
                        for (int i = 0; i < sEmailTo.Length; ++i)
                        {
                            if (sEmailTo[i] != null && sEmailTo[i] != "")
                            {
                                MailAddress toAddress = new MailAddress(sEmailTo[i], sEmailSendToName);
                                message.To.Add(toAddress);


                            }
                        }
                    }

                    switch (iPriority)
                    {
                        case 1:
                            message.Priority = MailPriority.High;
                            break;
                        case 3:
                            message.Priority = MailPriority.Low;
                            break;
                        default:
                            message.Priority = MailPriority.Normal;
                            break;
                    }


                    //message.Headers.Add("X-SMTPAPI", xmstpapiJson);

                    //smtpClient.SendCompleted += SendCompletedCallback;
                    //const string state = "test1";

                    message.Subject = sSubject;
                    message.IsBodyHtml = true;
                    message.Body = sMessage;

                    //smtpClient.SendAsync(message, state);
                    smtpClient.Send(message);
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
c# smtp sendgrid
2个回答
5
投票

我明白你的意思,smtpapi-csharp 项目根本没有实现这个概念.. 但这是一件小事。 (这个公用事业项目的价值一开始就值得怀疑)。

这里唯一重要的部分确实被注释掉了。

//message.Headers.Add("X-SMTPAPI", xmstpapiJson);

应该是,

message.Headers.Add("X-SMTPAPI", @"{ ""asm_group_id"" : 777, ""asm_groups_to_display"" : [777] }"); 

本质上,您只是将 json 分配给此标头。 文档提供了此示例

{
  "asm_groups_to_display": [1, 2, 3]
}

[1, 2, 3]
是一个整数数组,与 GroupId 相关。


或者,

分叉 git 并将以下内容添加到

Header.cs

/// <summary>
///     This sets which groups to display on the Manage Preferences page of an email.  You can find further documentation about ASM here:
///     https://sendgrid.com/docs/API_Reference/SMTP_API/suppressions.html
/// </summary>
/// <param name="ids">ASM groups to display applied to the message</param>
public void SetAsmGroupsToDisplay(params int[] ids)
{
    _settings.AddArray(new List<string> {"asm_groups_to_display"}, ids);
}

构建并更新您的 csproj 参考以使用您的分叉项目。

然后,像这样调用

SetAsmGroupsToDisplay

private static string XsmtpapiHeaderAsJson()
{
    var header = new Header();
    header.SetAsmGroupId(777);
    header.SetAsmGroupsToDisplay(777); // SetAsmGroupsToDisplay(new int[] {777}) works too
    return header.JsonString();
}

当然,使用方法:

message.Headers.Add("X-SMTPAPI", XsmtpapiHeaderAsJson());

...当你让它工作时,不要忘记添加拉取请求。


0
投票

SendGrid C# 库现在已将 ASM(高级订阅管理)实现为“SendGridMessage”对象的属性:

SendGridMessage message = MailHelper.CreateSingleTemplateEmail(from, to, templateId, dynamicTemplateData);
message.Asm = new ASM() { GroupId = 123, GroupsToDisplay = new List<int>() { 123, 456 } };
© www.soinside.com 2019 - 2024. All rights reserved.