Send Email And Get The SMTP Settings From File In ASP.NET Core Web Application

In this blog, we will see how to send email and get the SMTP settings from file in Asp.Net Core Web Application.

Using a Asp.NET Core Web application, it is very easy to send an email and get the SMTP settings (SMTP Server, From Address and Alias(Display Name)) from file.
 
The purpose of this blog is about how to get SMTP settings from file, so email content (Subject and Message) is simple. Follow the below steps for that.
 
For this example, we are going to use,
  • Microsoft Visual Studio Community 2019.
Now, let’s create an Asp.NET Core Web Application,
 
Step 1
 
First, click on the option Create a New Project. After that, we select the Asp.NET Core Web Application.
 
Send Email And Get The SMTP Settings From File In ASP.NET Core Web Application
 
Step 2
 
Let’s give a name to our Project.

Send Email And Get The SMTP Settings From File In ASP.NET Core Web Application
 
Step 3
 
Let’s select the empty template and disable the option Configure for HTTPS, for this example, we don’t need to configure HTTPS.
Send Email And Get The SMTP Settings From File In ASP.NET Core Web Application
Our project is going be like this,
 
Send Email And Get The SMTP Settings From File In ASP.NET Core Web Application
 
Step 4
 
Now, we will change our Startup.cs file.
 
We need to configure Mvc Services and the Access to our appsettings.json file. The IConfiguration interface is responsible for access the appsettings file, it is obtained in class constructor by Dependency Injection.
 
Startup.cs
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using Microsoft.Extensions.Configuration;  
  5. using Microsoft.Extensions.DependencyInjection;  
  6. namespace WebApplicationSendEmail {  
  7.     public class Startup {  

  8.         public IConfiguration Configuration {  
  9.             get;  
  10.         }  

  11.         public Startup(IConfiguration configuration) {  
  12.             Configuration = configuration;  
  13.         }  

  14.         // This method gets called by the runtime. Use this method to add services to the container.  
  15.         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940  
  16.         public void ConfigureServices(IServiceCollection services) {  
  17.             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  18.         }  

  19.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  20.         public void Configure(IApplicationBuilder app, IHostingEnvironment env) {  
  21.             if (env.IsDevelopment()) {  
  22.                 app.UseDeveloperExceptionPage();  
  23.             }  
  24.             app.UseMvc(routes => {  
  25.                 routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");  
  26.             });  
  27.         }  
  28.     }  
  29. }  
Step 5
 
Now, we need to add SMTP settings in appsetings file.
 
Appsettings.file
  1. {  
  2.     "Logging": {  
  3.         "LogLevel": {  
  4.             "Default""Warning"  
  5.         }  
  6.     },  
  7.     "AllowedHosts""*",  
  8.     //SMTP settings  
  9.     "SMTP": {  
  10.         "Host""YOUR_HOST",  
  11.         "From""YOUR_ADDRESS",  
  12.         "Alias""MyWebSite"  
  13.     }  
  14. }  
Don’t forget, change Host, From and Alias according you need.
 
Step 6
 
Let’s create the folders called “Controllers”, “Helper”, “Model”, “Views” and “Home”, the controller called “HomeController”, the classes called “EmailHelper”, “EmailModel” and the view called “Index”.
 
Right-click on Project (“WebApplicationSendEmail”) and go to Add.
 
Send Email And Get The SMTP Settings From File In ASP.NET Core Web Application
 
Index.cshtml
  1. @{  
  2. ViewData["Title"] = "Send Email";  
  3. }  
  4. <h1>Send Email</h1>  
  5.    <form action="~/Home/SendEmail">  
  6.    <button type="submit">Send Email</button>  
  7. </form>  
EmailModel.cs
  1. namespace WebApplicationSendEmail.Model {  
  2.     public class EmailModel {  
  3.         public EmailModel(string to, string subject, string message, bool isBodyHtml) {  
  4.             To = to;  
  5.             Subject = subject;  
  6.             Message = message;  
  7.             IsBodyHtml = isBodyHtml;  
  8.         }  
  9.         public string To {  
  10.             get;  
  11.         }  
  12.         public string Subject {  
  13.             get;  
  14.         }  
  15.         public string Message {  
  16.             get;  
  17.         }  
  18.         public bool IsBodyHtml {  
  19.             get;  
  20.         }  
  21.     }  
  22. }  
Note that we get the IConfiguration Interface in the class constructor by Dependency Injection.
 
HomeController.cs
  1. using Microsoft.AspNetCore.Mvc;  
  2. using Microsoft.Extensions.Configuration;  
  3. using WebApplicationSendEmail.Helper;  
  4. using WebApplicationSendEmail.Model;  
  5. namespace WebApplicationSendEmail.Controllers {  
  6.     public class HomeController: Controller {  
  7.         private EmailHelper _emailHelper;  
  8.         public HomeController(IConfiguration iConfiguration) {  
  9.             _emailHelper = new EmailHelper(iConfiguration);  
  10.         }  
  11.         public IActionResult Index() {  
  12.             return View();  
  13.         }  
  14.         public IActionResult SendEmail() {  
  15.             var emailModel = new EmailModel("destination_email@test.com"// To  
  16.                 "Email Test"// Subject  
  17.                 "Sending Email using Asp.Net Core."// Message  
  18.                 false // IsBodyHTML  
  19.             );  
  20.             _emailHelper.SendEmail(emailModel);  
  21.             return RedirectToAction("Index");  
  22.         }  
  23.     }  
  24. }  
EmailHelper.cs
  1. using Microsoft.Extensions.Configuration;  
  2. using System.Net.Mail;  
  3. using System.Text;  
  4. using WebApplicationSendEmail.Model;  
  5. namespace WebApplicationSendEmail.Helper {  
  6.     public class EmailHelper {  

  7.         private string _host;  
  8.         private string _from;  
  9.         private string _alias;  

  10.         public EmailHelper(IConfiguration iConfiguration) {  
  11.             _host = iConfiguration.GetSection("SMTP").GetSection("Host").Value;  
  12.             _from = iConfiguration.GetSection("SMTP").GetSection("From").Value;  
  13.             _alias = iConfiguration.GetSection("SMTP").GetSection("Alias").Value;  
  14.         }  

  15.         public void SendEmail(EmailModel emailModel) {  
  16.             try {  
  17.                 using(SmtpClient client = new SmtpClient(_host)) {  
  18.                     MailMessage mailMessage = new MailMessage();  
  19.                     mailMessage.From = new MailAddress(_from, _alias);  
  20.                     mailMessage.BodyEncoding = Encoding.UTF8;  
  21.                     mailMessage.To.Add(emailModel.To);  
  22.                     mailMessage.Body = emailModel.Message;  
  23.                     mailMessage.Subject = emailModel.Subject;  
  24.                     mailMessage.IsBodyHtml = emailModel.IsBodyHtml;  
  25.                     client.Send(mailMessage);  
  26.                 }  
  27.             } catch {  
  28.                 throw;  
  29.             }  
  30.         }  
  31.     }  
  32. }  
Now let’s start the Application.
 
Result
 
Browser
 
Send Email And Get The SMTP Settings From File In ASP.NET Core Web Application
 Inbox - Email received
 
Send Email And Get The SMTP Settings From File In ASP.NET Core Web Application
 
In this blog, we have explored how to send an email and get the SMTP settings from appsettings file.
 
If you face a problem with this code, please comment below.