Render Razor View To String In ASP.NET Core To Send E-mail With MailKit

How To Render Razor View To String

This post is a continuation of the last post I wrote couple of days ago about How To Send E-mail In ASP.Net Core Using Mailkit.
From the last post, we were able to send a successful e-mail using MailKit with no problem. Therefore, in this post I’m going to cover how to use the RazorViewEngine to render Views, and get the string content to be used as an email template.
Since we’ll be using the same solution, let’s download it from github first and make sure it’s build properly.

Add HTML View Template

First we’ll need to add a new view called “Welcome” as shown below.
Adding the welcome view to be used in the html email template
Next, we’ll use the following html as the template for the email. If you are planning on using this template for more than one type of emails, the best thing would be to create a layout and use that with the views. But since this is just to demonstrate how to render the view into a string to send the html content we’ll keep it simple with just welcome view.


  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Demystifying Email Design</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>


<body style="margin: 0; padding: 0;">
    <table  class=" table table-hover" align="center" cellpadding="0" cellspacing="0" width="1200">
        <tr>
            <td align="center" style="padding: 40px 0 30px 0; background-color:cadetblue">
                <img src="https://pngimage.net/wp-content/uploads/2018/06/sample-logo-png-transparent-background-4.png" alt="Creating Email Magic" width="300" height="230" style="display: block; text-align:center" />
            </td>
        </tr>
        <tr>
            <td bgcolor="#ffffff">
                <table  class=" table table-hover" cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                        <td width="260" valign="top">
                            <h3>How to get more customers online?</h3>
                            <p>
                                <img src="https://www.tibco.com/blog/wp-content/uploads/2014/09/shutterstock_1674174502.jpg" />
                                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget orci rhoncus, iaculis nulla vel, lobortis neque. Vivamus sodales dui eu ante aliquet, eu venenatis nisi vehicula. Donec id sollicitudin diam. Vivamus sodales odio in consectetur ultricies. Vestibulum sollicitudin id lectus quis sollicitudin. Sed lorem neque, tincidunt ut risus ac, aliquam laoreet lectus. Proin dictum risus volutpat, tincidunt elit sit amet, ornare lacus. Pellentesque et purus eu est aliquam dignissim. Donec commodo semper mauris sit amet ultricies. Cras et hendrerit elit, at interdum nulla. Ut at varius est. Aenean luctus interdum lorem ac dignissim.
                            </p>
                        </td>
                        <td style="font-size: 0; line-height: 0; border-left:solid 4px; color:#e5e4e4" width="20">
                            &nbsp;
                        </td>
                        <td width="260" valign="top">
                            <h3>How to attract new customers?</h3>
                            <p>
                                <img src="https://biz-architect.com/wp-content/uploads/2016/05/Customers.png" />
                                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget orci rhoncus, iaculis nulla vel, lobortis neque. Vivamus sodales dui eu ante aliquet, eu venenatis nisi vehicula. Donec id sollicitudin diam. Vivamus sodales odio in consectetur ultricies. Vestibulum sollicitudin id lectus quis sollicitudin. Sed lorem neque, tincidunt ut risus ac, aliquam laoreet lectus. Proin dictum risus volutpat, tincidunt elit sit amet, ornare lacus. Pellentesque et purus eu est aliquam dignissim. Donec commodo semper mauris sit amet ultricies. Cras et hendrerit elit, at interdum nulla. Ut at varius est. Aenean luctus interdum lorem ac dignissim.
                            </p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td style="background-color:#b4b2b2">


                <table  class=" table table-hover" cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                        <td style="color: #ffffff; font-family: Arial, sans-serif; font-size: 14px;">
                            &reg; Company, Copyright 2019<br />
                            <a href="#" style="color: #ffffff;"><font color="#ffffff">Unsubscribe</font></a> to this newsletter instantly
                        </td>
                        <td>
                            <table  class=" table table-hover" border="0" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td>
                                        <a href="http://www.twitter.com/">
                                            <img src="http://assets.stickpng.com/thumbs/580b57fcd9996e24bc43c53e.png" alt="Twitter" width="38" height="38" style="display: block;" border="0" />
                                        </a>
                                    </td>
                                    <td style="font-size: 0; line-height: 0;" width="20">&nbsp;</td>
                                    <td>
                                        <a href="http://www.Facebook.com/">
                                            <img src="http://www.transparentpng.com/thumb/facebook-logo-png/background-facebook-logo-5.png" alt="Facebook" width="38" height="38" style="display: block;" border="0" />
                                        </a>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>

Now that we have the view in place, make sure to add the action method for that view in the home controller class as shown below.

      public IActionResult Welcome()
        {
            return View();
        }

Add helper to render view into string

  • Right click on the solution and add a new folder called “Helpers”
    Adding new helper folder for rendering html view to string
  • Next, let’s add a new class called “ViewsToStringOutputHelper.cs” and copy and paste the following code snippet into it.
    Adding new RenderRazorViewToString

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.AspNetCore.Mvc.ViewEngines;
    using Microsoft.AspNetCore.Mvc.ViewFeatures;
    using System.IO;
    
    namespace SendEmailInAspNetCore.Helpers
    {
        public class ViewsToStringOutputHelper
        {
            public static string RenderRazorViewToString(Controller controller, string viewName, object model)
            {
                controller.ViewData.ModelState.Clear();
                controller.ViewData.Model = model;
    
                using (var sw = new StringWriter())
                {
                    ViewEngineResult viewResult = null;
                    var engine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
    
                    viewResult = engine.FindView(controller.ControllerContext, viewName, false);
    
                    var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw, new HtmlHelperOptions());
                    viewResult.View.RenderAsync(viewContext);
    
                    return sw.GetStringBuilder().ToString();
                }
            }
        }
    }
    

Render the view into a string

  • Next, let’s modified the Contact action method to use the new helper to render the view into a string.
  • First, I need a new variable for the email body string object and another flag to determine whether to use the email template or not
                        string emailBody = string.Empty;
                        bool useEmailTemplate = false;
         
  • Then, let’s add a new condition to determine if we should use the template or not as shown below
                        if (useEmailTemplate)
                        {
                            emailBody = ViewsToStringOutputHelper.RenderRazorViewToString(this, "Welcome", null);
                        }
                        else
                        {
                            emailBody = contactViewModel.Message + " Message was sent by: " + contactViewModel.Name + " E-mail: " + contactViewModel.Email;
    
                        }
                        message.Body = new TextPart(TextFormat.Html)
                        {
                            Text = emailBody
                        };      
    

Sending a new email using a rendered view to string template

  • First, we’ll send an email with the useEmailTemplate flag set to false and then another with it set to true. As you can see below, the new html template indeed used in the second email.
    Final email showing both html email template and plain text

How To Send E-mail In ASP.Net Core Using Mailkit

Send E-mail In ASP.Net Core

I am working on this new project where I need to implement a way for us to send newsletters to users on a weekly basis which requires some sort of ways to sending html content in the email.
Well, I’ve always wanted to use this library called Mailkit, so I thought it would be a good opportunity to put a quick post together and sample application to try it first before implementing it in the project. Of course, if you don’t want to use MailKit, you could always make use of the .Net Core SMTP Client.

For simplicity, I’ll keep this post short and focus solely on how to send the e-mail in .NET Core using MailKit.

  • First, create a new ASP.NET Core application with the following name “SendEmailInAspNetCore”
    “File” –>”New” –>”Project”
  • A “New Project” dialog will open. Select “.NET Core” in the left panel inside the Visual C# menu.
    Create send email project to send E-mail In ASP.Net Core
  • Next, select the Web Application (Model-View-Controller) template as shown below.
    Select the right template for the project to send E-mail In ASP.Net Core
  • Once the project is created, make sure to build it and verify that there’s no error before you proceed further.
  • Now, that we know we have a working project to start with, let’s use NuGet to add the “Mailkit” library to the project.
  • Add a new class in the Model folder called “ContactViewModel.cs. In it, we’ll have the following properties to collect the email form data.
    using System.ComponentModel.DataAnnotations;
    
    namespace SendEmailInAspNetCore.Models
    {
        public class ContactViewModel
        {
            [Required]
            [StringLength(60, MinimumLength = 5)]
            public string Name { get; set; }
            [Required]
            [EmailAddress]
            public string Email { get; set; }
            [Required]
            public string Subject { get; set; }
            [Required]
            public string Message { get; set; }
        }
    }
    
    
  • To keep this simple, let’s update the contact view with a simple contact form as shown below.
    
    @model SendEmailInAspNetCore.Models.ContactViewModel
    @{
        ViewData["Title"] = "Contact";
    }
    <h3>Send E-mail In ASP.Net Core 2.1 Using MailKit</h3>
    
    <div class="has-error" col-md-12>
        <form method="post">
            <div class="row">
                <div class="form-group col-md-4">
                    <label asp-for="Name">Name:</label>
                    <input asp-for="Name" class="form-control" />
                    <span asp-validation-for="Name" class="text-muted"></span>
                </div>
            </div>
            <div class="row">
                <div class="form-group col-md-4">
                    <label asp-for="Email">Email:</label>
                    <input asp-for="Email" class="form-control" />
                    <span asp-validation-for="Email" class="text-muted"></span>
                </div>
            </div>
            <div class="row">
                <div class="form-group col-md-4">
                    <label asp-for="Subject">Subject:</label>
                    <input asp-for="Subject" class="form-control" />
                    <span asp-validation-for="Subject" class="text-muted"></span>
                </div>
            </div>
            <div class="row">
                <div class="form-group col-md-6">
                    <label asp-for="Message">Message:</label>
                    <textarea rows="8" cols="20" asp-for="Message" class="form-control"></textarea>
                    <span asp-validation-for="Message" class="text-muted"></span>
                </div>
            </div>
            <div>
                <button type="submit" class="btn btn-success">Send Message</button>
            </div>
        </form>
    </div>
    
    
  • Let’s update the controller to add a new action to post the contact form to.
     [HttpPost]
     public IActionResult Contact(ContactViewModel contactViewModel)
     {
       if (ModelState.IsValid)
       {
         try
            {
              //instantiate a new MimeMessage
              var message = new MimeMessage();
              //Setting the To e-mail address
              message.To.Add(new MailboxAddress("E-mail Recipient Name", "recipient@domail.com"));
              //Setting the From e-mail address
              message.From.Add(new MailboxAddress("E-mail From Name", "from@domain.com"));
              //E-mail subject 
              message.Subject = contactViewModel.Subject;
              //E-mail message body
              message.Body = new TextPart(TextFormat.Html)
              {
                Text = contactViewModel.Message + " Message was sent by: " + contactViewModel.Name + " E-mail: " + contactViewModel.Email
              };
    
              //Configure the e-mail
              using (var emailClient = new SmtpClient())
              {
                emailClient.Connect("smtp.gmail.com", 587, false);
                emailClient.Authenticate("emailaddress@gmail.com", "password");
                emailClient.Send(message);
                emailClient.Disconnect(true);
               }
            }
            catch (Exception ex)
            {
              ModelState.Clear();
              ViewBag.Message = $" Oops! We have a problem here {ex.Message}";
            }
        }
        return View();
     }
    
  • Let’s run the application now, click on the contact menu item
  • Below is an example error when trying to send the email with a bad credentials.
    Displaying the error message in E-mail In ASP.Net Core
  • Let’s try to send a valid email now. As you can see below the e-mail was received with no problem.
    Showing how message was successfully sent out in the project E-mail In ASP.Net Core

Source Code is available for download on GitHub

51 Business Listing Websites For Local Businesses

If you are a business owner, you should know and understand the importance of having your business listed in the top major search engines on the internet. With the competition being so fierce, those business owners who understand and take action will always win. Therefore, I have compiled a list of all the major platforms for you to list your business and start growing your fan base.

I come up with this list and started using it on some local businesses that I have worked with in the past. Since most of them provide free submission, I thought others would be interest in making use of them to bring more visibility to their business. Getting your business listed on as many online local directories as possible is the best and quickest way to make sure potential new customers find you when searching for products and services related to your business.

Before I start by sharing this list with you. I want you to know that this will not be an easy or quick task. It will require some effort and time on your part to go to each of those website and submit your business information.

Promote on search engines for Local Businesses

Basic checklist to follow when submitting your business those platform

  • NAP – Some of those platforms will on require the basic NAP for your business which is your business’s Name, Address & Phone number. Therefore, make sure that information is the same on all them.
  • Business Description – If you are allowed to submit a business description, take the time to make sure you write something meaningful about the services your business provide. DO NOT LEAVE IT BLANK. This is where you highlight your company’s history and services offered. BE CREATIVE!
  • Website Link – This one of the most important piece of information you MUST provide if your company has a website. This is a great way to drive more traffic to your website and help people who want to learn about your business discover what you have to offer.
  • Pictures And Videos – Majority of listing platforms allow businesses to post pictures and short videos about their services. Take on the opportunity and showcase your business best. Let the world know why they should care about your services or products.
  1. Upamile
  2. Google
  3. Bing
  4. Yelp
  5. Facebook
  6. Better Business Bureau
  7. Angie’s List
  8. Merchant Circle
  9. LinkedIn
  10. YP.com
  11. Whitepages
  12. Superpages.com
  13. Yellowbook
  14. CitySearch
  15. MapQuest/Yext
  16. Local.com
  17. Foursquare
  18. CitySlick
  19. USDirectory.com
  20. BizJournals.com
  21. TeleAtlas
  22. Discover Our Town
  23. EZ Local
  24. CityVoter
  25. Manta
  26. UsCity
  27. InfoUSA
  28. Infignos
  29. Get Fave
  30. My Huckleberry
  31. Yellowee
  32. Brownbook
  33. Magic Yellow
  34. CitySquares
  35. Map Creator
  36. Judy’s Book
  37. TripAdvisor
  38. Thumbtack
  39. YellowPagesGoesGreen.org
  40. Home Advisor
  41. ShowMeLocal
  42. ChamberofCommerce.com
  43. Yellowbot
  44. Hotfrog
  45. Brownbook
  46. InsiderPages
  47. Bizwiki
  48. Business Local Pages
  49. iBegin
  50. Opendi
  51. Sitejabber