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 separated 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.

{
	"Email": {
		"ToEmails": [
			"test1@test.com",
			"test2@test.com",
			"test3@test.com"
		]
	}
}
// Build configuration
IConfigurationRoot _config = new ConfigurationBuilder()
	.SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
	.AddJsonFile("appsettings.json", false)
	.Build();

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

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

If you are aiming to use this in a console application then you’ll need to install the following NuGet packages.

Microsoft.Extensions.Configuration    
Microsoft.Extensions.Configuration.Binder

1 Comment

Nayan · 21 June 2022 at 7:44 am

Can you help me to mock this “_config.GetSection(“Email:ToEmails”).Get<List>();” with moq for unit testing? I am having hard time to figure this out

Leave a Reply

Avatar placeholder

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