I have written an email service class to sendout email to multiple email ids. Which sends email to multiple email ids using smtpclient class.Here is the method which sends the emails.
private async Task SendEmail(EmailOptions emailOptions)
{
MailMessage mail = new MailMessage
{
Subject = emailOptions.Subject,
Body = emailOptions.Body,
From = new MailAddress(_mailSettings.SenderAddress, _mailSettings.SenderDisplayName),
IsBodyHtml = _mailSettings.IsBodyHTML
};
foreach (var toEmail in emailOptions.ToEmails)
{
mail.To.Add(toEmail);
}
NetworkCredential networkCredential = new NetworkCredential(_mailSettings.UserName, _mailSettings.Password);
SmtpClient smtpClient = new SmtpClient
{
Host = _mailSettings.Host,
Port = _mailSettings.Port,
EnableSsl = _mailSettings.EnableSSL,
UseDefaultCredentials = _mailSettings.UseDefaultCredentials,
Credentials = networkCredential
};
mail.BodyEncoding = Encoding.Default;
await smtpClient.SendMailAsync(mail);
smtpClient.Dispose();
}
private string GetEmailBody(string templateName)
{
const string templatePath = @"EmailTemplates/{0}.html";
var body = File.ReadAllText(string.Format(templatePath, templateName));
return body;
}
And this is the update place holder in email template method
private string UpdatePlaceHolders(string text, List<KeyValuePair<string, string>> keyValuePairs)
{
if (!string.IsNullOrEmpty(text) && keyValuePairs != null)
{
foreach (var placeholder in keyValuePairs)
{
if (text.Contains(placeholder.Key))
{
text = text.Replace(placeholder.Key, placeholder.Value);
}
}
}
return text;
}
public class EmailOption
{
public string ToEmail { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public List<KeyValuePair<string, string>> PlaceHolders { get; set; }
}
Here is the emailbody method, where I am filling the template with the username from the placeholder. For each email i send the content will be same except the salutation. Hi Mr X, Hi Mr Y. I can send mails to multiple email ids but how do i change/ specify different only the salutation in the email. In my template, I have placed a placeholder
Dear <username>
like Dear Myusername