Okay, this is how I have setup my Email Configuration in my project. This code is for your sample reference and I really hope it helps you out.
The appsettings.json is as follows:
"EmailConfiguration":
{
"Host": "smtp.gmail.com",
"Port": 587,
"MailAddress": "[email protected]",
"MailDisplayName": "Your Display Name",
"Username": "[email protected]",
"Password": "yourpassword"
}
The EmailConfiguration class which is basically a model to hold your settings from the config file will look like:
public class EmailConfiguration
{
public string Host { get; set; }
public int Port { get; set; }
public string MailAddress { get; set; }
public string MailDisplayName { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
Theinterface in which you would declare your generic SendEmail method will look like:
public interface IEmailManager
{
bool SendEmail<T>(string subject, string body, string fromAddress, List<string> toAddresses, List<string> ccAddresses, List<string> bccAddresses, string name = "", List<string> filePaths = null, string htmlFile = "", T data = default(T), bool apptUpdate=false);
}
And finally the class that will implement the above interface will look like:
public class EmailManager : IEmailManager
{
private readonly EmailConfiguration _emailSettings;
public EmailManager(EmailConfiguration emailConfiguration)
{
_emailSettings = emailConfiguration;
}
public bool SendEmail<T>(string subject, string body, string fromAddress, List<string> toAddresses, List<string> ccAddresses, List<string> bccAddresses, string name = "", List<string> filePaths = null, string htmlFile = "", T data = default(T), bool apptUpdate = false)
{
string host = _emailSettings.Host;
SmtpClient smtpClient = new SmtpClient(_emailSettings.Host, _emailSettings.Port);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
MailAddress from = new MailAddress(_emailSettings.MailAddress, _emailSettings.MailDisplayName);
smtpClient.Credentials = new NetworkCredential(_emailSettings.Username, _emailSettings.Password);
MailMessage myMail = new MailMessage();
myMail.From = from;
//Rest logic to send email
}
}
Make sure your register the class in your Startup.cs under the ConfigureServices method:
var emailSettingsSection = Configuration.GetSection("EmailConfiguration");
services.Configure<EmailConfiguration>(emailSettingsSection);
This method can be used for your other config settings also.
IOptions<ApplicationSettings>in the constructor instead of justApplicationSettings? Also have you ensured that theConfiguration.GetSectionis correct and returns the correct values?