Search code examples
asp.netasp.net-mvcasp.net-corehtml-email

Creating Email Template in ASP.NET MVC


I am trying to create EmailTemplates. I have been able to write the controller codes and also created a .txt file in a folder but when the mail is been sent, the users receive it as a HTML code.

Controller code

   public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, 
                                            Firstname = model.Firstname, Surname = model.Surname, Gender = model.Gender};
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                string body = string.Empty;
                var root = AppDomain.CurrentDomain.BaseDirectory; using (var reader = new System.IO.StreamReader(root + @"/EmailTemplates/ConfirmAccount.txt"))
                {
                    string readFile = reader.ReadToEnd();
                    string StrContent = string.Empty;
                    StrContent = readFile;
                    //Assing the field values in the template
                    StrContent = StrContent.Replace("[Firstname]", user.Firstname);
                    StrContent = StrContent.Replace("[Surname]", user.Surname);
                    StrContent = StrContent.Replace("[Code]", callbackUrl);
                    StrContent = StrContent.Replace("[Year]", DateTime.Now.Year.ToString());
                    body = StrContent.ToString();
                }
                await UserManager.SendEmailAsync(user.Id, "Confirm Your Account", body);
 return View("DisplayEmail");
            }
            AddErrors(result);
        }

        
        return View(model);
    }

Below is the .txt file content

<!doctype html>     
<html lang="tr">
<head>
 <meta charset="utf-8">
 </head>     
 <body>
   <p>Dear [Firstname]  [Surname],</p>
   <p>Kindly Confirm your Email by clicking the link below</p>
   <p>[Code]</p>
 </body>

The output is in form of a HTML.


Solution

  • The better way to send HTML formatted Email your code will be in "ConfirmAccount.htm"

    <!doctype html>     
    <html lang="tr">
    <head>
     <meta charset="utf-8">
     </head>     
     <body>
       <p>Dear [Firstname]  [Surname],</p>
       <p>Kindly Confirm your Email by clicking the link below</p>
       <p>[Code]</p>
     </body>
    

    Read HTML file Using System.IO.File.ReadAllText. get all HTML code in string variable.

    string Body = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("EmailTemplates/ConfirmAccount.htm"));
    

    Replace a Particular string with your custom value.

    Body = Body.Replace("[Firstname]", user.Firstname);
    

    Call SendEmail(string Body) Function and do a procedure to send an email. Replace the Session email and Configuration app settings with your ones.

    public static void SendEmail(string Body)
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress(Session["Email"].Tostring());
                message.To.Add(ConfigurationSettings.AppSettings["RequesEmail"].ToString());
                message.Subject = "Request from " + SessionFactory.CurrentCompany.CompanyName + " to add a new supplier";
                message.IsBodyHtml = true;
                message.Body = Body;
    
                SmtpClient smtpClient = new SmtpClient();
                smtpClient.UseDefaultCredentials = true;
    
                smtpClient.Host = ConfigurationSettings.AppSettings["SMTP"].ToString();
                smtpClient.Port = Convert.ToInt32(ConfigurationSettings.AppSettings["PORT"].ToString());
                smtpClient.EnableSsl = true;
                smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationSettings.AppSettings["USERNAME"].ToString(), ConfigurationSettings.AppSettings["PASSWORD"].ToString());
                smtpClient.Send(message);
            }
    

    You can check out in message.IsBodyHtml = true SendEmailAsyn Method