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

3 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

    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

      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.

Leave a Reply

Your e-mail address will not be published. Required fields are marked *