Deprecated: Function create_function() is deprecated in D:\home\site\wwwroot\wp-content\plugins\wp-spamshield\wp-spamshield.php on line 2033

Reading Lists from appsettings.json

I’ve been using the SendGrid API for a project and I was trying to be lazy and read multiple email addresses to send to from a single parameter in appsettings.json with the email addresses seperated by a semicolon. Strangely this only sends to the first email in the string so I needed to do a little more work and store the emails in an array in appsettings.json and to read this into a list and then loop through it adding each address individually.

appsettings.json


{
  "Email": {
    "ToEmails": [
      "test1@test.com",
      "test2@test.com",
      "test3@test.com"
    ]
}

Program.cs


List<string> emailTo = _config.GetSection("Email:ToEmails").Get<List<string>>()

foreach (string email in emailTo)
{
	sendGridMessage.AddTo(new EmailAddress(email));
}

4 Comments

Jim · 29th March 2019 at 2:38 pm

Any idea how to do this with combined email address/display name?

    Shinigami · 29th March 2019 at 4:12 pm


    Deprecated: Function create_function() is deprecated in D:\home\site\wwwroot\wp-content\plugins\wp-spamshield\wp-spamshield.php on line 2033

    Depends on how you’ve got these stored in your appsettings.json file, if it’s like the below then you can load them into a dictionary rather than a list.

    “Emails”: {
    “test@test.com”: “Mr Test”,
    “test2@test.com”: “Ms Test”
    }

    Dictionary<string, string> emails = _config.GetSection(“Emails”).Get<Dictionary<string, string>>();

      Jim · 29th March 2019 at 5:45 pm


      Deprecated: Function create_function() is deprecated in D:\home\site\wwwroot\wp-content\plugins\wp-spamshield\wp-spamshield.php on line 2033

      Thanks. I ended up using one string like “test@test.com:Joe Test” and using string.split(‘:’) after I pulled it out of appsettings.json.

        Bryan · 10th May 2019 at 8:41 pm


        Deprecated: Function create_function() is deprecated in D:\home\site\wwwroot\wp-content\plugins\wp-spamshield\wp-spamshield.php on line 2033

        You could also create a class with the and change the structure of your json a little too
        public class EmailConfig
        {
        public string Address { get; set; }

        public string To { get; set; }
        }

        “Emails”: [
        {
        “Address”: “test@test.com”,
        “To”: “Mr. Test”
        },
        {
        “Address”: “test2@test.com”,
        “To”: “Mr. Test2”
        }
        ]

        var emails = _config.GetSection(“Emails”).Get<List>();

        This way you stay strongly typed and don’t have to do string manipulation

Leave a Reply

Your email address will not be published. Required fields are marked *