Wednesday, February 11, 2015

Asp.Net MVC Razor Email Template

Asp.Net MVC Razor Email Template 


1- Create EmailTemplates Folder
---------------
2- Create Html Page Template Inject Razor Replacement Variables :

<h1>Test Email From NADY</h1>

<div>
    Dear @Model.UserFullName,

    Your User Name : @Model.UserName
</div>


<div>
    Your Account Start Date : @Model.RegDate
</div>

<h1>@Model.SiteUrl</h1>

---------------
3- Install RazorEngine Nuget Package:
From Nuget Consol : PM> Install-Package RazorEngine -Version 3.5.3
https://www.nuget.org/packages/RazorEngine/3.5.3
// You can also check "razormachine"->  Install-Package razormachine

More Info :
https://github.com/Antaris/RazorEngine
http://antaris.github.io/RazorEngine/
https://razorengine.codeplex.com/
----------------
4- Create your Model :
- Called "TestEmailTemplateViewModel" :

    public class TestEmailTemplateViewModel
    {
        public string UserFullName { get; set; }
        public string UserName { get; set; }
        public string RegDate { get; set; }
        public string SiteUrl { get; set; }
    }
----------------
5- Create Your test Controller "TestEmailTemplateController":

 public ActionResult TestEmailTemplate()
        {
            return View();
        }

        [HttpPost]
        public ActionResult TestEmailTemplate(string fortest)
        {
            ParsingTemplate();
            return View();
        }

        private void ParsingTemplate()
        {
            //OR System.Web.Hosting.HostingEnvironment.MapPath(@"~/EmailTemplates/EmailTemplateTest.html");
            string templateFilePath = System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplates/EmailTemplateTest.html");
            var templateAsString = System.IO.File.ReadAllText(templateFilePath);

            var myViewModel = new TestEmailTemplateViewModel
            {
                UserFullName = "Mohamed Nady",
                UserName = "NADY",
                SiteUrl = "http://www.mohnady.com",
                RegDate = DateTime.Now.ToString()
            };

            var body = RazorEngine.Engine.Razor.RunCompile(templateAsString, "templateKey", typeof(TestEmailTemplateViewModel), myViewModel);
            // You Can Now Test your Returned Html Message Body (Check Body Value)

            SendEmail("naadydev@gmail.com", "m.nady@najran.gov.sa", "testEmail", body);

            //=====================================================
            //var result = RazorEngine.Engine.Razor.RunCompile("templateKey", typeof(TestEmailTemplateViewModel), myViewModel);
            //============= Simple Example ========================
            // string templateString = "Hello @Model.Name, welcome to RazorEngine!";
            // var result = RazorEngine.Engine.Razor.RunCompile(templateString, "templateKey", null, new { Name = "World" });
            //------------------------------
            //string templateString = "Hello @Model.Name, welcome to RazorEngine!";
            //string templateFileLocation = "C:/mytemplate.cshtml";
            //var result = RazorEngine.Engine.Razor.RunCompile(new LoadedTemplateSource(templateString, templateFileLocation), "templateKey", null, new { Name = "World" });
            // More Info: https://github.com/Antaris/RazorEngine
            //            http://antaris.github.io/RazorEngine/
            //======================================================
        }

        private void SendEmail(string from, string to, string subject, string body)
        {
            // Sending .net Email Code 
        }

-----------------------
6- OR you can just Use Normal .Net Way using 'MailDefinition'

        /// <summary>
        /// Other .Net Way To Send Email Using HTML Template File 
        /// Using Magic Of 'MailDefinition'
        /// </summary>
        private void OtherDotNetNormalWayToSendEmailTemplate()
        {
            //How To Use Html Template To Send Email
            string htmlBodyTemplatePath = System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplates/EmailTemplateTest.html");
            MailDefinition mailDefinition = new MailDefinition();
            mailDefinition.BodyFileName = Server.MapPath(htmlBodyTemplatePath);
            mailDefinition.From = "xxx";
            mailDefinition.CC = "xxx";
            mailDefinition.IsBodyHtml = true;
            mailDefinition.Subject = "xxxx";
            //------------
            System.Collections.Specialized.ListDictionary replacements = new System.Collections.Specialized.ListDictionary();
            replacements.Add("<%RegDate%>", "XXX");
            replacements.Add("<%UserName%>", "XXXX");
            replacements.Add("<%UserFullName%>", "XXX");
            //------------        
            System.Net.Mail.MailMessage msg = mailDefinition.CreateMailMessage("XXX", replacements, new System.Web.UI.Control());
            msg.From = new System.Net.Mail.MailAddress("XX", "XXX");
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Send(msg);

        }




No comments: