Send Email Using Templates In ASP.NET Core (2024)

In this article, we will discuss how to send emails using a Template file in ASP.NET Core Application. Sending email using Template file is similar to sending emails using plain text. The only difference is that now, the source of the content is a text file rather than direct content for email.

If you don’t know how to send email in ASP.NET Core applications, please refer to my previous article Configure Email Service In ASP.NET Core Using MailKit. Let's assume, we have already configured email service in ASP.NET Core application.

Milestones

  1. Create a Simple Email Template.
  2. Configure Email Setting in ASP.NET Core Application.
  3. Read content from Email Template using StreamReader()
  4. Personalize Email Content
  5. Send Email to User

Creating a Simple Email TemplateWe will keep the template file separate so that we can change the file design and content anytime. Let's keep these template files under wwwroot => Templates => EmailTemplate.

Step 1

For this, create a new folder named Templates under wwwroot folder.

Step 2

Create a new folder named Email Template under Templates folder.

Step 3Add a new Item in Email Template (right click on Email Template folder >> add New Item).

Step 4Select ASP.NET Core and then HTML Page.

Step 5Set a name for the HTML file. In my case, I have named it as Welcome_EmailTemplate.html (But I will be usingConfirm_Account_Registration.htmlfor demo purposes whose design is the same with a different file name).

Send Email Using Templates In ASP.NET Core (1)

Once you have created Email Templates, the Solution Explorer looks like below. (In my case, there are 5 Email Templates)

Send Email Using Templates In ASP.NET Core (2)

Now, you can write your own design codes using inline CSS and HTML to create Email. In my case, the template looks like this -

Send Email Using Templates In ASP.NET Core (3)

  1. <htmlxmlns="http://www.w3.org/1999/xhtml">
  2. <head>
  3. <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
  4. <title>WelcomeEmailfromTCP</title>
  5. </head>
  6. <body>
  7. <tablewidth="100%"border="0"cellspacing="0"cellpadding="0">
  8. <tr>
  9. <tdalign="center"valign="top"bgcolor="#ffe77b"style="background-color:#ffe77b;">
  10. <br>
  11. <br>
  12. <tablewidth="600"border="0"cellspacing="0"cellpadding="0">
  13. <tr>
  14. <tdheight="70"align="left"valign="middle"></td>
  15. </tr>
  16. <tr>
  17. <tdalign="left"valign="top"><imgsrc="http://localhost:2131/Templates/EmailTemplate/images/top.png"width="600"height="13"style="display:block;"></td>
  18. </tr>
  19. <tr>
  20. <tdalign="left"valign="top"bgcolor="#564319"style="background-color:#564319;font-family:Arial,Helvetica,sans-serif;padding:10px;">
  21. <divstyle="font-size:36px;color:#ffffff;">
  22. <b>{0}</b>
  23. </div>
  24. <divstyle="font-size:13px;color:#a29881;">
  25. <b>{1}:ASP.NETCoreDempApp</b>
  26. </div>
  27. </td>
  28. </tr>
  29. <tr>
  30. <tdalign="left"valign="top"bgcolor="#ffffff"style="background-color:#ffffff;">
  31. <tablewidth="100%"border="0"cellspacing="0"cellpadding="0">
  32. <tr>
  33. <tdalign="center"valign="middle"style="padding:10px;color:#564319;font-size:28px;font-family:Georgia,'TimesNewRoman',Times,serif;">
  34. Congratulations!<small>Youareregistered.</small>
  35. </td>
  36. </tr>
  37. </table>
  38. <tablewidth="95%"border="0"align="center"cellpadding="0"cellspacing="0">
  39. <tr>
  40. <tdwidth="40%"align="center"valign="middle"style="padding:10px;">
  41. <imgsrc="http://localhost:2131/Templates/EmailTemplate/images/Weak_Password.gif"width="169"height="187"style="display:block">
  42. </td>
  43. <tdalign="left"valign="middle"style="color:#525252;font-family:Arial,Helvetica,sans-serif;padding:10px;">
  44. <divstyle="font-size:16px;">
  45. Dear{2},
  46. </div>
  47. <divstyle="font-size:12px;">
  48. Thankyouforshowingyourinterestinourwebsite.
  49. Allyouneedtodoisclickthebuttonbelow(itonlytakesafewseconds).
  50. Youwon’tbeaskedtologintoyouraccount–we'resimplyverifyingownershipofthisemailaddress.
  51. <hr>
  52. <center>
  53. <buttontype="button"title="ConfirmAccountRegistration"style="background:#1b97f1">
  54. <ahref="{6}"style="font-size:22px;padding:10px;color:#ffffff">
  55. ConfirmEmailNow
  56. </a>
  57. </button>
  58. </center>
  59. </div>
  60. </td>
  61. </tr>
  62. </table>
  63. <tablewidth="100%"border="0"cellspacing="0"cellpadding="0">
  64. <tr>
  65. <tdalign="center"valign="middle"style="padding:5px;">
  66. <imgsrc="http://localhost:2131/Templates/EmailTemplate/images/divider.gif"width="566"height="30">
  67. </td>
  68. </tr>
  69. </table>
  70. <tablewidth="100%"border="0"align="center"cellpadding="0"cellspacing="0"style="margin-bottom:15px;">
  71. <tr>
  72. <tdalign="left"valign="middle"style="padding:15px;font-family:Arial,Helvetica,sans-serif;">
  73. <divstyle="font-size:20px;color:#564319;">
  74. <b>Pleasekeepyourcredentialsconfidentialforfutureuse.</b>
  75. </div>
  76. <divstyle="font-size:16px;color:#525252;">
  77. <b>Email:</b>{2}
  78. <br/>
  79. <b>Username:</b>{3}
  80. <br/>
  81. <b>Password:</b>{4}
  82. </div>
  83. </td>
  84. </tr>
  85. </table>
  86. <tablewidth="100%"border="0"cellspacing="0"cellpadding="0"style="margin-bottom:10px;">
  87. <tr>
  88. <tdalign="left"valign="middle"style="padding:15px;background-color:#564319;font-family:Arial,Helvetica,sans-serif;">
  89. <divstyle="font-size:20px;color:#fff;">
  90. <b>Updateyourpasswordnow.</b>
  91. </div>
  92. <divstyle="font-size:13px;color:#ffe77b;">
  93. Weakpasswordsgetstolenandleadtohackedaccounts.CelebrateWorldPasswordDaywithanew,strongpassword.
  94. <br>
  95. <br>
  96. <ahref="#"style="color:#ffe77b;text-decoration:underline;">CLICKHERE</a>TOCHANGEPASSOWORD
  97. </div>
  98. </td>
  99. </tr>
  100. </table>
  101. <tablewidth="95%"border="0"align="center"cellpadding="0"cellspacing="0">
  102. <tr>
  103. <tdwidth="50%"align="left"valign="middle"style="padding:10px;">
  104. <tablewidth="75%"border="0"cellspacing="0"cellpadding="4">
  105. <tr>
  106. <tdalign="left"valign="top"style="font-family:Verdana,Geneva,sans-serif;font-size:14px;color:#000000;">
  107. <b>FollowUsOn</b>
  108. </td>
  109. </tr>
  110. <tr>
  111. <tdalign="left"valign="top"style="font-family:Verdana,Geneva,sans-serif;font-size:12px;color:#000000;">
  112. <tablewidth="100%"border="0"cellspacing="0"cellpadding="0">
  113. <tr>
  114. <tdwidth="33%"align="left"valign="middle">
  115. <ahref="https://twitter.com"title="Facebook">
  116. <imgsrc="http://localhost:2131/Templates/EmailTemplate/images/tweet48.png"width="48"height="48">
  117. </a>
  118. </td>
  119. <tdwidth="34%"align="left"valign="middle">
  120. <ahref="https://linkedin.com"title="Linkedin">
  121. <imgsrc="http://localhost:2131/Templates/EmailTemplate/images/in48.png"width="48"height="48">
  122. </a>
  123. </td>
  124. <tdwidth="33%"align="left"valign="middle">
  125. <ahref="https://facebook.com"title="Facebook">
  126. <imgsrc="http://localhost:2131/Templates/EmailTemplate/images/face48.png"width="48"height="48">
  127. </a>
  128. </td>
  129. </tr>
  130. </table>
  131. </td>
  132. </tr>
  133. </table>
  134. </td>
  135. <tdwidth="50%"align="left"valign="middle"style="color:#564319;font-size:11px;font-family:Arial,Helvetica,sans-serif;padding:10px;">
  136. <b>Hours:</b>Mon-Fri9:30-5:30,Sat.9:30-3:00,Sun.Closed<br>
  137. <b>CustomerSupport:</b><ahref="mailto:[emailprotected]"style="color:#564319;text-decoration:none;">[emailprotected]</a><br>
  138. <br>
  139. <b>CompanyAddress</b><br>
  140. CompanyURL:<ahref="http://www.yourcompanyname.com"target="_blank"style="color:#564319;text-decoration:none;">http://www.yourcompanyname.com</a>
  141. </td>
  142. </tr>
  143. </table>
  144. </td>
  145. </tr>
  146. <tr>
  147. <tdalign="left"valign="top"><imgsrc="http://localhost:2131/Templates/EmailTemplate/images/bot.png"width="600"height="37"style="display:block;"></td>
  148. </tr>
  149. </table>
  150. <br>
  151. <br>
  152. </td>
  153. </tr>
  154. </table>
  155. </body>
  156. </html>

Now, our Email Template is ready.

Scenario - I : Verifying User's Email Ownership on Registration

We need to send a confirmation email to verify the ownership of the email to the user, just after first registration with his/her email on our application.

The process is,

  • Collect user details from Registration Form
  • Register Method of Account Controller of type [HttpPost] creates a new user using the following code.
    1. //Take user details from Registration Form ie. model carries data from Registration form to here
    2. var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

    3. //CreateAsync inside UserManager creates new user when userdetails and password supplied.
    4. var result = await _userManager.CreateAsync(user, model.Password);
  • Generate unique code for new user details.
    1. var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  • A unique random callbackUrl is generated using the generated code and UserId.
    1. var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
  • Send callbackUrl to the user via email.
    1. string Message = "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>";
    2. //Send Email to User
    3. await _emailSender.SendEmailAsync(model.Email, subject, messageBody);
  • When user clicks the send callback URL, he/she is sent back to the ConfirmEmail Method of Account Controller.
  1. //Find User Details by userId
  2. var user = await _userManager.FindByIdAsync(userId);
  3. if (user == null)
  4. {
  5. return View("Error");
  6. }
  7. var result = await _userManager.ConfirmEmailAsync(user, code);
  8. ViewData["Message"] = "Your email has been confirmed. Please Login now. ";
  9. ViewData["MessageValue"] = "1";
  • This line will match the received user details and code via callbackUrl and sets ConfirmedEmail to true in database.

Now, during this process, if we want to send email using our custom Email Templates, we need to

  1. Read content of Email Template
  2. Read User Details received from User Registration Form.
  3. Pass User Details to contents of Email Template.
  4. Replace {0}, {1}, {2} with respective values.
  5. Send email to user. (Using Mail Kit for now)

Reading Contents from Template File

Step 1

Get Information about the web Hosting Environment where our application is running.

  1. privatereadonlyUserManager<ApplicationUser>_userManager;
  2. privatereadonlySignInManager<ApplicationUser>_signInManager;
  3. privatereadonlyIEmailSender_emailSender;
  4. privatereadonlyISmsSender_smsSender;
  5. privatereadonlyILogger_logger;
  6. privatereadonlystring_externalCookieScheme;
  7. privateIHostingEnvironment_env;
  8. publicAccountController(
  9. UserManager<ApplicationUser>userManager,
  10. SignInManager<ApplicationUser>signInManager,
  11. IOptions<IdentityCookieOptions>identityCookieOptions,
  12. IEmailSenderemailSender,
  13. ISmsSendersmsSender,
  14. ILoggerFactoryloggerFactory,
  15. IHostingEnvironmentenv)
  16. {
  17. _userManager=userManager;
  18. _signInManager=signInManager;
  19. _externalCookieScheme=identityCookieOptions.Value.ExternalCookieAuthenticationScheme;
  20. _emailSender=emailSender;
  21. _smsSender=smsSender;
  22. _logger=loggerFactory.CreateLogger<AccountController>();
  23. _env=env;
  24. }

Step 2get wwwroot Folder

  1. var webRoot = _env.WebRootPath; //get wwwroot Folder

Step 3Get TemplateFile located at wwwroot/Templates/EmailTemplate/Register_EmailTemplate.html

  1. //GetTemplateFilelocatedatwwwroot/Templates/EmailTemplate/Register_EmailTemplate.html
  2. varpathToFile=_env.WebRootPath
  3. +Path.DirectorySeparatorChar.ToString()
  4. +"Templates"
  5. +Path.DirectorySeparatorChar.ToString()
  6. +"EmailTemplate"
  7. +Path.DirectorySeparatorChar.ToString()
  8. +"Confirm_Account_Registration.html";

Step 4Initialie BoduBuilder()

  1. var builder = new BodyBuilder();

Step 5Read Content of Template file using StreamReader and append to BodyBuilder()

  1. using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
  2. {

  3. builder.HtmlBody = SourceReader.ReadToEnd();

  4. }

Passing value and Formatting the Content of Template with Dynamic Values

Step 1use string.Format(format item, dynamic values as parameters) In our case, {x} values in Templates are to replace by dynamic values.

  1. //{0}:Subject
  2. //{1}:CurrentDateTime
  3. //{2}:Email
  4. //{3}:Username
  5. //{4}:Password
  6. //{5}:Message
  7. //{6}:callbackURL

Code Snippet

  1. stringmessageBody=string.Format(builder.HtmlBody,
  2. subject,
  3. String.Format("{0:dddd,dMMMMyyyy}",DateTime.Now),
  4. model.Email,
  5. model.Email,
  6. model.Password,
  7. Message,
  8. callbackUrl
  9. );

Send Email using MailkitIf you don’t know how to send email using Mail kit in ASP.NET Core Applications please refer to my previous blog. For now I am skipping setting up email service.

  1. await_emailSender.SendEmailAsync(model.Email,subject,messageBody);
  2. //SuccessMessageViewData["Message"]=$"Pleaseconfirmyouraccountbyclickingthislink:<ahref='{callbackUrl}'class='btnbtn-primary'>ConfirmationLink</a>";
  3. ViewData["MessageValue"]="1";

await _emailSender.SendEmailAsync(model.Email, subject, messageBody); line will send email to user email.

Code used in Register Method of Account Controller

  1. //POST:/Account/Register
  2. [HttpPost]
  3. [AllowAnonymous]
  4. [ValidateAntiForgeryToken]
  5. publicasyncTask<IActionResult>Register(RegisterViewModelmodel,stringreturnUrl=null)
  6. {
  7. ViewData["ReturnUrl"]=returnUrl;
  8. if(ModelState.IsValid)
  9. {
  10. varuser=newApplicationUser{UserName=model.Email,Email=model.Email};
  11. varresult=await_userManager.CreateAsync(user,model.Password);
  12. //varuser=await_userManager.FindByEmailAsync(model.Email);
  13. if(result.Succeeded)
  14. {
  15. //Sendanemailwiththislink
  16. varcode=await_userManager.GenerateEmailConfirmationTokenAsync(user);
  17. varcallbackUrl=Url.Action(nameof(ConfirmEmail),"Account",new{userId=user.Id,code=code},protocol:HttpContext.Request.Scheme);
  18. //EmailfromEmailTemplate
  19. stringMessage="Pleaseconfirmyouraccountbyclicking<ahref=\""+callbackUrl+"\">here</a>";
  20. //stringbody;
  21. varwebRoot=_env.WebRootPath;//getwwwrootFolder
  22. //GetTemplateFilelocatedatwwwroot/Templates/EmailTemplate/Register_EmailTemplate.html
  23. varpathToFile=_env.WebRootPath
  24. +Path.DirectorySeparatorChar.ToString()
  25. +"Templates"
  26. +Path.DirectorySeparatorChar.ToString()
  27. +"EmailTemplate"
  28. +Path.DirectorySeparatorChar.ToString()
  29. +"Confirm_Account_Registration.html";
  30. varsubject="ConfirmAccountRegistration";
  31. varbuilder=newBodyBuilder();
  32. using(StreamReaderSourceReader=System.IO.File.OpenText(pathToFile))
  33. {
  34. builder.HtmlBody=SourceReader.ReadToEnd();
  35. }
  36. //{0}:Subject
  37. //{1}:DateTime
  38. //{2}:Email
  39. //{3}:Username
  40. //{4}:Password
  41. //{5}:Message
  42. //{6}:callbackURL
  43. stringmessageBody=string.Format(builder.HtmlBody,
  44. subject,
  45. String.Format("{0:dddd,dMMMMyyyy}",DateTime.Now),
  46. model.Email,
  47. model.Email,
  48. model.Password,
  49. Message,
  50. callbackUrl
  51. );
  52. await_emailSender.SendEmailAsync(model.Email,subject,messageBody);
  53. ViewData["Message"]=$"Pleaseconfirmyouraccountbyclickingthislink:<ahref='{callbackUrl}'class='btnbtn-primary'>ConfirmationLink</a>";
  54. ViewData["MessageValue"]="1";
  55. _logger.LogInformation(3,"Usercreatedanewaccountwithpassword.");
  56. returnRedirectToLocal(returnUrl);
  57. }
  58. ViewData["Message"]=$"Errorcreatinguser.Pleasetryagainlater";
  59. ViewData["MessageValue"]="0";
  60. AddErrors(result);
  61. }
  62. //Ifwegotthisfar,somethingfailed,redisplayform
  63. returnView(model);
  64. }

Appplication Execution and Output

Step 1Now let's rebuild the soution and run the application.

Step 2

Lets register as a New user /Account/Register
Send Email Using Templates In ASP.NET Core (4)

Once we register as new user, a confirmation email is sent on the registred email. Upon checking the email inbox, we receive email like this -

Send Email Using Templates In ASP.NET Core (5)

We receive the personalized email sent from the Demo ASP.NET Core Application.

Scenerio where we need Email Templates

  • Send personalized emails to all/selected users for events and news.
  • Newsletter
  • Notices and Call for events
  • Welcome Email to New Users.
  • Automatic Monthly report to Admins and Staffs.
  • and many more....

SummarySo far, we have learned how to send personalized emails to users creating Email Templates .

You may also like

  • How to configure Email Services in ASP.NET Core Applications.
  • How to export data to Excel from Web API in ASP.NET Core using Kendo UI
  • Sorting and Grouping in Kendo Grid using Web API in ASP.NET Core Application
  • Call Web API Using JQuery AJAX In ASP.NET Core Web Applications
  • How to create Image Thumbnail in ASP.NET Web Application
Send Email Using Templates In ASP.NET Core (2024)

FAQs

How do I send an email template in .NET core? ›

Sending Emails in ASP.NET Core
  1. Step #1 – Create an email template.
  2. Step #2 – Create a new model.
  3. Step #3 – Make changes to IMailService and MailService.
  4. Step #4 – Add a new method in the Mail controller.
Mar 9, 2023

Are email templates effective? ›

Email templates can be an extremely effective way to save time and improve the likelihood that your sales message will land with your prospects. Your emails will look better and take less time to craft —and you'll never be caught staring anxiously at a blank screen.

How to send email using email template in C#? ›

var mailMessage = new MailMessage { From = new MailAddress("email"), Subject = "subject", Body = "<h1>Hello</h1>", IsBodyHtml = true, }; mailMessage. To. Add("recipient"); smtpClient. Send(mailMessage);

How to send an email in ASP.NET Core? ›

To send an email in ASP.NET Core Web API, we will use an interface and a class to define a method for sending an email. Through dependency injection, we will call that method in an API controller.

How do I send an email using a template? ›

Insert a template
  1. Open Gmail and click Compose.
  2. Click More. Templates.
  3. To insert a template, under Insert template, choose a saved template to insert in your email.
  4. Compose the rest of your message and click Send.

Is SmtpClient obsolete? ›

Allows applications to send email by using the Simple Mail Transfer Protocol (SMTP). The SmtpClient type is obsolete on some platforms and not recommended on others; for more information, see the Remarks section.

What is one of the benefits of using templates for your email? ›

Templates are an essential component of email marketing campaigns. They provide a structured framework that ensures consistency in your email design and messaging. One of the benefits of using templates for your email marketing campaigns is the ability to save time.

Why you should use email templates? ›

You have control over the primary messaging when you use templates so that each correspondence will be professional. Also, templates contain contact and other relevant information in the same place, making it easier for customers to find what they're looking for when perusing emails.

What is the purpose of using email templates? ›

Email templates are pre-written messages that you can use to communicate with your clients, customers, or colleagues. They can save you time, improve your consistency, and enhance your professionalism.

How to send email automatically using ASP.NET C#? ›

Credentials = new NetworkCredential("SMTP_USERNAME", "SMTP_PASSWORD"); smtp. Send(new MailMessage("fromAddress@example.com", "toAddress@example.com", "Hello world", "testbody")); Run the code, and if everything seems to be in order, you are free to start testing!

How to send email in asp net C# with example? ›

  1. SmtpClient client = new SmtpClient("smtp.gmail.com", 587); C# Copy.
  2. Credentials = new System. Net. NetworkCredential("username", "password"); C# Copy.
  3. EnableSsl = true; C# Copy.
  4. Send(message); C# Copy.
Feb 1, 2024

What is the best way to send mail in C#? ›

The most common way of sending emails from your C# application is by using a Simple Mail Transfer Protocol (SMTP) server. But, as C# is not able to communicate with and instruct an SMTP host server on its own, you will need the . NET framework.

How to validate email in asp net Core? ›

ASP.NET Core offers various approaches to implement email validation. One common method is using Data Annotations, such as the [EmailAddress] attribute, to decorate your model properties. By applying [EmailAddress] to the Email property, you instruct ASP.NET Core to validate the input as an email address.

How to send email in C# .NET using SMTP and SendGrid? ›

How to send SMTP emails in C# . NET using SendGrid
  1. Verify your email sender in the SendGrid app and create an API key.
  2. Connect to SendGrid's SMTP server at smtp.sendgrid.net and use port 587.
  3. Authenticate against the SMTP server using "apikey" as the username and the actual API key as the password.
Feb 22, 2022

How do I add an email template to my email? ›

Use a Template

In the New Message, click More options. Click Templates. Click the template you wish to use. Add or edit the new message as needed.

How to send email in .NET Core 6? ›

. NET 6.0 - Send an Email via SMTP with MailKit
  1. Install MailKit via NuGet. .NET Core CLI: dotnet add package MailKit. ...
  2. Send an HTML email in . NET 6.0. ...
  3. Send a plain text email in .NET 6.0. ...
  4. Send SMTP email with Gmail, Hotmail, Office 365 or AWS SES. ...
  5. Wrap it up in an Email Service.
Mar 11, 2022

How do I send an email using SendGrid in .NET core? ›

Then follow these steps:
  1. Log in to your SendGrid account.
  2. Select Settings -> Sender Authentication.
  3. Select “Single Sender Verification.”
  4. Click on the “Get Started” button.
  5. Create a Sender by specifying the sender details.
  6. Click on the “Verify Single Sender” button.
Mar 2, 2023

How do I create an email template in eM client? ›

eM Client mail templates

In the Mail Templates section, click on the Mail Templates... button and then click New. Be sure to give the template a name, otherwise, you won't be able to save it. Then you may pick the color , font, set a background image, add any attachments, and write up a template mail.

Top Articles
Latest Posts
Article information

Author: Rubie Ullrich

Last Updated:

Views: 6574

Rating: 4.1 / 5 (72 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Rubie Ullrich

Birthday: 1998-02-02

Address: 743 Stoltenberg Center, Genovevaville, NJ 59925-3119

Phone: +2202978377583

Job: Administration Engineer

Hobby: Surfing, Sailing, Listening to music, Web surfing, Kitesurfing, Geocaching, Backpacking

Introduction: My name is Rubie Ullrich, I am a enthusiastic, perfect, tender, vivacious, talented, famous, delightful person who loves writing and wants to share my knowledge and understanding with you.