ASP.NET CORE Send Email Uing SMTP Server (GMAIL)

Introduction

This blog post will walk you through the steps to send an email in ASP.NET Core. Here we will see how to use the Gmail server to send emails with ASP.NET Core.

ASP.NET CORE Send Email Uing SMTP Server (GMAIL)

Getting Started

Sending email in .Net core is as easy as in. Net framework, here we will demonstrate how to send email in ASP.NET CORE using Visual Studio 2022.Net8.0. This demonstration will work on both ASP.NET Core Web Application and ASP.NET Core Web API. Following the below steps, we are going to demonstrate.

  • Create ASP.NET Web Application
  • Installation of required libraries
  • Configure SMTP
  • Create A Service Class
  • Register for the Service Class
  • Create a controller to use Service Class

Develop Website Project Template

The following steps will help you to create an ASP.NET Web Application project.

  • Open Visual Studio and then select Create a new project.
  • The New Project window will appear, find and choose ASP.NET Core Web Application or ASP.NET Core Web API and confirm that C# is listed in the languages for that choice, then select Next.
  • Name the application netcoresmtp then Click on the OK button.
  • The additional information window will appear, click on the Next button.
  • You are done with ASP.NET core application creation now, write whatever you want to code then from the Visual Studio menu, select Debug > Start Without Debugging to run the web app locally.
asp net core send email

.NET.CORE Send Email



Installation of Required Libraries

Earlier the System.Net.Mail.dll was used to send mail in. NETFRAMEWORK, in .Net core the below libraries are used to send mails.

  • MailKit : is an open-source cross-platform .NET mail-client library based on MimeKit.
  • MimeKit: also, an open-source cross-platform .net library for parsing messages using the Multipurpose Internet Mail Extension (MIME).
Follow the below steps to install the mentioned libraries.
  • Go to the Manage NuGet Package
  • In the search box of the Browse tab, enter “MailKit”. The below library will appear in the list. Then click on the install button that resides on the right panel.
        net core mail
  • The same search for MimeKit and install it. The MimeKit will look like the below image.
     sending email net core

Configure SMTP

After installing the libraries, the Gmail SMTP settings need to be stored in the appsettins.json to use in further. The following are the Gmail SMTP configurations.

 {  
  "SmtpSettings":   
  {  
   "Server": "smtp.gmail.com", //SMTP SERVER GMAIL  
   "Port": 587, // or 465  
   "SenderName": "Display name of sender mail",  
   "SenderEmail": "sender email address",  
   "Username": "sender email address",  
   "Password": "sender password"  
  }  
 }  

.NET CORE SMTP

Copy the above SMTP Gmail settings and paste them inside the appsettings.json file and your code inside the appsettings.json should look like below.

 {  
  "Logging": {  
   "LogLevel": {  
    "Default": "Information",  
    "Microsoft.AspNetCore": "Warning"  
   }  
  },  
  "AllowedHosts": "*",  
  "SmtpSettings": {  
   "Server": "smtp.gmail.com", //SMTP SERVER GMAIL  
   "Port": 587, // or 465  
   "SenderName": "Kailash's Blog",  
   "SenderEmail": "kailashblogs@gmail.com",  
   "Username": "kailashblogs@gmail.com",  
   "Password": "sender password"  
  }  
 }  

.NET CORE MAIL

Create A Service Class

Create a class with the name EmailService in the project which will play a role of service, this service class will contain codes to send email. Copy the code below and past in the EmailService class.

 private readonly IConfiguration _config;  
 public EmailService(IConfiguration config)  
 {  
   _config = config;  
 }
 //asp net core send email
 public async Task SendEmailAsync(string[] toEmails, string[] ccEmails, string subject, string message)  
 {  
   MimeMessage emailMessage = new MimeMessage();  
   emailMessage.From.Add(new MailboxAddress(_config["SmtpSettings:SenderName"], _config["SmtpSettings:SenderEmail"]));  
   foreach (string toEmail in toEmails)  
   {  
     emailMessage.To.Add(new MailboxAddress("", toEmail));  
   }  
   foreach (string ccEmail in ccEmails)  
     emailMessage.Cc.Add(new MailboxAddress("", ccEmail));  
   emailMessage.Subject = subject;  
   emailMessage.Body = new TextPart("plain") { Text = message };  
   using (var client = new SmtpClient())  
   {  
     await client.ConnectAsync(_config["SmtpSettings:Server"], int.Parse(_config["SmtpSettings:Port"]), MailKit.Security.SecureSocketOptions.StartTls);  
     await client.AuthenticateAsync(_config["SmtpSettings:Username"], _config["SmtpSettings:Password"]);  
     await client.SendAsync(emailMessage);  
     await client.DisconnectAsync(true);  
   }  
 }  

ASP.NET CORE Send Email

After copying and pasting the code into your EmailService class the following namespace is required to take reference.

 using MimeKit;  
 using MailKit.Net.Smtp;  

Register for the Service Class

After creating the service class, the service class has to register in the application or project to use it further. The below code registers the class.

 builder.Services.AddSingleton<EmailService>();  

Copy the above code and paste it into the Program.cs class. after copying and pasting the above code your code is in the Program.cs file should look like below.

 var builder = WebApplication.CreateBuilder(args);  
 // Add services to the container.  
 builder.Services.AddRazorPages();  
 var app = builder.Build();  
 // Configure the HTTP request pipeline.  
 if (!app.Environment.IsDevelopment())  
 {  
   app.UseExceptionHandler("/Error");  
   // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
   app.UseHsts();  
 }  
 app.UseHttpsRedirection();  
 app.UseStaticFiles();  
 app.UseRouting();  
 app.UseAuthorization();  
 app.MapRazorPages();  
 app.Run();  

Create Control Class

The last and final step is creating a controller in the project or application, if your application is a web application then your controller will contain two methods one is HTTP GET, and another is HTTP POST like below. The HTTP GET method will be used to land the email view and the HTTP POST method will be used to submit the view content or send emails. Or if your application is an API then only the HTTP POST method is enough to send email.

Following are the codes for the controller. this can be used in an ASP.NET CORE Web Application

 namespace ASPNETCORESMTP  
 {  
   public class EmailController:Controller  
   {  
     private readonly EmailService _emService;  
     public EmailController(EmailService emService)  
     {  
       _emService = emService;  
     }  
     [HttpGet]  
     public IActionResult SendEmail()  
     {  
       return View();  
     }  
     [HttpPost]  
     public async Task<IActionResult> SendEmail(string toAddress,string ccAddress,string Subject,string Message)  
     {  
       string[] ToEmail= toAddress.Split(',');  
       string[] CCEmail = ccAddress.Split(',');  
       if (ModelState.IsValid)  
       {  
         await _emService.SendEmailAsync(ToEmail,CCEmail,Subject,Message);  
       }  
       return View();  
     }  
   }  
 }  

The below code is for the ASP.NET CORE WEB API controller.

 using Microsoft.AspNetCore.Mvc;  
 namespace ASPNETCORESMTP  
 {  
   public class EmailController:Controller  
   {  
     private readonly EmailService _emService;  
     public EmailController(EmailService emService)  
     {  
       _emService = emService;  
     }  
     [HttpPost]  
     public async Task<string> SendEmail(string toAddress,string ccAddress,string Subject,string Message)  
     {  
       string[] ToEmail= toAddress.Split(',');  
       string[] CCEmail = ccAddress.Split(',');  
       if (ModelState.IsValid)  
       {  
         await _emService.SendEmailAsync(ToEmail,CCEmail,Subject,Message);  
       }  
       return "Email Sent Successfully";  
     }  
   }  
 }  

.NET CORE Send Email

Summary

Sending email in .Net core is as easy as the .Net framework, I hope you have enjoyed this and that this blog post is helpful to you.

Thanks


Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

نموذج الاتصال