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.
Step 2
Let’s give a name to our Project.
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.
Our project is going be like this,
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
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- namespace WebApplicationSendEmail {
- public class Startup {
- public IConfiguration Configuration {
- get;
- }
- public Startup(IConfiguration configuration) {
- Configuration = configuration;
- }
-
-
- public void ConfigureServices(IServiceCollection services) {
- services.AddTransient<EmailHelper>();
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
- }
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
- if (env.IsDevelopment()) {
- app.UseDeveloperExceptionPage();
- }
- app.UseMvc(routes => {
- routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
- });
- }
- }
- }
Step 5
Now, we need to add SMTP settings in appsetings file.
Appsettings.file
- {
- "Logging": {
- "LogLevel": {
- "Default": "Warning"
- }
- },
- "AllowedHosts": "*",
-
- "SMTP": {
- "Host": "YOUR_HOST",
- "From": "YOUR_ADDRESS",
- "Alias": "MyWebSite"
- }
- }
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.
Index.cshtml
- @{
- ViewData["Title"] = "Send Email";
- }
- <h1>Send Email</h1>
- <form action="~/Home/SendEmail">
- <button type="submit">Send Email</button>
- </form>
EmailModel.cs
- namespace WebApplicationSendEmail.Model {
- public class EmailModel {
- public EmailModel(string to, string subject, string message, bool isBodyHtml) {
- To = to;
- Subject = subject;
- Message = message;
- IsBodyHtml = isBodyHtml;
- }
- public string To {
- get;
- }
- public string Subject {
- get;
- }
- public string Message {
- get;
- }
- public bool IsBodyHtml {
- get;
- }
- }
- }
Note that we get the IConfiguration Interface in the class constructor by Dependency Injection.
HomeController.cs
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using WebApplicationSendEmail.Helper;
- using WebApplicationSendEmail.Model;
- namespace WebApplicationSendEmail.Controllers {
- public class HomeController: Controller {
- private EmailHelper _emailHelper;
- public HomeController(EmailHelper emailHelper) {
- _emailHelper = emailHelper;
- }
- public IActionResult Index() {
- return View();
- }
- public IActionResult SendEmail() {
- var emailModel = new EmailModel("[email protected]",
- "Email Test",
- "Sending Email using Asp.Net Core.",
- false
- );
- _emailHelper.SendEmail(emailModel);
- return RedirectToAction("Index");
- }
- }
- }
EmailHelper.cs
- using Microsoft.Extensions.Configuration;
- using System.Net.Mail;
- using System.Text;
- using WebApplicationSendEmail.Model;
- namespace WebApplicationSendEmail.Helper {
- public class EmailHelper {
- private string _host;
- private string _from;
- private string _alias;
public EmailHelper(IConfiguration iConfiguration)
{
var smtpSection = iConfiguration.GetSection("SMTP");
if (smtpSection != null)
{
_host = smtpSection.GetSection("Host").Value;
_from = smtpSection.GetSection("From").Value;
_alias = smtpSection.GetSection("Alias").Value;
}
}
- public void SendEmail(EmailModel emailModel) {
- try {
- using(SmtpClient client = new SmtpClient(_host)) {
- MailMessage mailMessage = new MailMessage();
- mailMessage.From = new MailAddress(_from, _alias);
- mailMessage.BodyEncoding = Encoding.UTF8;
- mailMessage.To.Add(emailModel.To);
- mailMessage.Body = emailModel.Message;
- mailMessage.Subject = emailModel.Subject;
- mailMessage.IsBodyHtml = emailModel.IsBodyHtml;
- client.Send(mailMessage);
- }
- } catch {
- throw;
- }
- }
- }
- }
Now let’s start the Application.
Result
Browser
Inbox - Email received
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.