How to send Razor View as a Email with Model in ASP.NET MVC?


I am trying to send email in ASP.NET MVC, but it is not a plain HTML string, I need to convert Razor View with Model into string and then send it as a HTML content in MVC. So, How can I convert Razor view in HTML string with Model and then send it in MVC email? Thanks


Asked by:- manish
0
: 4989 At:- 12/9/2019 12:34:41 PM
MVC C# razor view as string in MVC send razor view in email







2 Answers
profileImage Answered by:- neena

You can create a class to convert view into string using C#

public static class RazorViewToStringHelper
    {
        public static string RenderViewToString(this Controller controller, string viewName, object model)
        {
            if (controller == null)
            {
                throw new ArgumentNullException("controller", "Extension method called on a null controller");
            }
            if (controller.ControllerContext == null)
            {
                return string.Empty;
            }
            controller.ViewData.Model = model;

            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            if (viewResult != null)
            {
                using (var sw = new StringWriter())
                {
                    var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                    viewResult.View.Render(viewContext, sw);
                    viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
                    return sw.GetStringBuilder().ToString();
                }
            }
            return null;
        }
    }

You can call the above HelperFunction as

string HTMLStringWithModel= RazorViewToStringHelper.RazorViewToString(this, "~/Views/Home/YourView.cshtml", YourModel);

YourModel= Model with Values, which is required in the View and provide full path to the Razor View.

Now you can send it as a body in Email as html string

      MailMessage Msg = new MailMessage();
      Msg.From = new MailAddress("senderEmailId@gmail.com","Sender Name");// replace with valid value
      Msg.Subject = "Contact";
      Msg.To.Add("Emailto@gmail.com"); //replace with correct values

      Msg.Body = HTMLStringWithModel; //here is the razor view body

      Msg.IsBodyHtml = true;
      Msg.Priority = MailPriority.High;
      SmtpClient smtp = new SmtpClient();
      smtp.Host = "smtp.gmail.com";
      smtp.Port = 587;
      smtp.Credentials = new System.Net.NetworkCredential("senderEmailId@gmail.com", "password");// replace with valid value
      smtp.EnableSsl = true;
      smtp.Timeout = 20000;

      smtp.Send(Msg);

Above code used from article "Send Email in ASP.NET MVC C# (With attachments)"

1
At:- 12/13/2019 12:23:43 PM


profileImage Answered by:- bhanu

The above answers work properly when working with .NET MVC to send Razor view as an email, if you want to send Razor view as an email in ASP.NET Core MVC you can use the below code

First, you will have to create Helper Class which will convert Razor view into HTML String

public static class ViewToStringRenderer
{
    public static async Task<string> RenderViewToStringAsync<TModel>(IServiceProvider requestServices, string viewName, TModel model)
    {
        var viewEngine = requestServices.GetRequiredService(typeof(IRazorViewEngine)) as IRazorViewEngine;
        ViewEngineResult viewEngineResult = viewEngine.GetView(null, viewName, false);
        if (viewEngineResult.View == null)
        {
            throw new Exception("Could not find the View file. Searched locations:\r\n" + string.Join("\r\n", viewEngineResult.SearchedLocations));
        }
        else
        {
            IView view = viewEngineResult.View;
            var httpContextAccessor = (IHttpContextAccessor)requestServices.GetRequiredService(typeof(IHttpContextAccessor));
            var actionContext = new ActionContext(httpContextAccessor.HttpContext, new RouteData(), new ActionDescriptor());
            var tempDataProvider = requestServices.GetRequiredService(typeof(ITempDataProvider)) as ITempDataProvider;

            using var outputStringWriter = new StringWriter();
            var viewContext = new ViewContext(
                actionContext,
                view,
                new ViewDataDictionary<TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model },
                new TempDataDictionary(actionContext.HttpContext, tempDataProvider),
                outputStringWriter,
                new HtmlHelperOptions());

            await view.RenderAsync(viewContext);

            return outputStringWriter.ToString();
        }
    }
}

Then in your Startup.cs -> ConfigureServices() , use below code to register above class:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Once you have the above configuration, you can use helper as below

string str = await ViewToStringRenderer.RenderViewToStringAsync(HttpContext.RequestServices, $"~/Views/Emails/MyEmailTemplate.cshtml", new MyEmailModel { Prop1 = "Hello", Prop2 = 23 });

That's it, hope it helps.

0
At:- 1/19/2022 10:57:59 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use