David
David

Reputation: 1105

Add template to email Body

I have email service like this:

public async Task Execute(string email, string subject, string message)
{
    try
    {
        string toEmail = string.IsNullOrEmpty(email)
                         ? _emailSettings.ToEmail
                         : email;
        MailMessage mail = new MailMessage()
        {
            From = new MailAddress(_emailSettings.UsernameEmail, "")
        };
        mail.To.Add(new MailAddress(toEmail));
        mail.CC.Add(new MailAddress(_emailSettings.CcEmail));

        mail.Subject = "Management System - " + subject;
        mail.Body = message;
        mail.IsBodyHtml = true;
        mail.Priority = MailPriority.High;

        using (SmtpClient smtp = new SmtpClient(_emailSettings.PrimaryDomain, _emailSettings.PrimaryPort))
        {
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential(_emailSettings.UsernameEmail, _emailSettings.UsernamePassword);
            smtp.EnableSsl = true;
            await smtp.SendMailAsync(mail);
        }
    }
    catch (Exception ex)
    {
        //do something here
    }
}

then I execute it into enother method:

public Task SendAsync(string email, string subject, string message)
{
    Execute(email, subject, message).Wait();
    return Task.FromResult(0);
}

and I have template email template who have items as:

<a  href="{{url}}" target="_blank" </a>

How can I call template in body and replace that {{url}} for some variable in my service? So instead mail.Body = message; change to mail.Body = template;

Upvotes: 0

Views: 1305

Answers (1)

Nisarg Shah
Nisarg Shah

Reputation: 14531

I generally keep a template with placeholders such as {0}, {1}, {2} etc, as they fit directly into string.Format. So while creating the email, instead of writing mail.Body = message, I use:

mail.Body = string.Format(template, placeholder1, placeholder2);

My template then looks like:

Hello {0},

... Please <a href="{1}">click here to do XYZ</a>...

Now there is a disadvantage of this method, which is that you must document that {0} in template corresponds to placeholder1 etc.

Alternatively you could use slightly verbose placeholders such as {FirstName} or {LastName}, and then replace them in the body of email using template.Replace("{FirstName}", user.FirstName).Replace("{LastName}", user.LastName).

Upvotes: 1

Related Questions