Search code examples
c#smtpsendgrid

Sendgrid unsubscribe preferences


I'm using Sendgrid and try to sending these emails with C# language. So, what i'm doing is configure the SMTP and API Keys in my apps, and boom, there goes the emails were sent.

The question is, How do I insert the Unsubscribe Preferences group in my X-SMTPAPI header? FYI, unsubscribe preferences is where you can choose which group you want to unsubscribe instead of global unsubscribe.

I already checked these links:

I also checked the library C# on their github. But none of these is made me clear.

I'm completely blind with JSON, GET, REQUEST, RESPONSE and such.

this is my C# code

        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;
                }
            }

Solution

  • I see what you mean, the smtpapi-csharp project simply doesn't have that concept implemented.. but it's a trivial matter. (the value of this utility project is questionable to begin with).

    Really the only piece of importance here is commented out.

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

    Should be,

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

    Essentially, you're just assigning json to this header. The Documentation provides this sample

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

    [1, 2, 3] is an array of integers, which correlates to GroupIds.


    Alternatively,

    fork the git and add the following to 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);
    }
    

    Build and update your csproj reference to use your forked project.

    then, call SetAsmGroupsToDisplay like so,

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

    and, of course, use the method:

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

    ... don't forgot to add a Pull Request when you get it working.