Sending e-mail is one of the methods we frequently use in software development.Today I will show you how to send an email using Gmai SMTP Server in .NETCore. To do this, we will create a Console App in .net core.I will use Visual Studio. To create an empty console app project, open Visual Studio =>Create a New Project , Select Console App template from the list that appears. Don't forget to check if the template  support C#.

    In order to send emails, we need to download a few packages to our project. Right click on the project and click on the Manage Nuget Packages menu. You need to download the MailKit package from there. We also need the Autofac package to use and resolve our classes. Download the Autofac package from there as well.

    Now that we have downloaded our packages to the project, we can start coding. To keep classes such as Abstract and Inteface in a single folder, I create a folder named Abstract and create an interface class called IEmailService in it. In this interface we are going to create a method which provides to send email.


      public  interface IEmailService
    {
      Task  SendEmail(string fromMail, string toMail, string htmlBody, string subject, string mailNotificationHeader);
    }  


      I will create a new folder to organize Concrete classes. I need a class which ı need to fill send method. So I am creating a class called Email manager. In this class, we will fill in the method that sends the Email.

 

   

 

       This is a console application, so the program will first start from the program.cs file . The Main method will be like this.


   

 private  async static Task  Main(string[] args)
    {

 

                      var containerBuilder = new ContainerBuilder();
        containerBuilder.RegisterType<EmailManager>().As<IEmailService>(); 

 

               var container = containerBuilder.Build(); 

 

                       string articleTitle = "How to make an email sending program with .net core ?";
        string editorName="Mustafa Ulas";
        string htmlBody = $"<p> Article Title:{articleTitle}</p> <p>Editor :{editorName} </p> <p> Date:{DateTime.Now} </p>"; 

 

                      string sender = "mustafaulas1986@gmail.com";
        string to = "mustafaulas@windowslive.com"; 

 

              var _mailService = container.Resolve<IEmailService>();

 

               var result =  _mailService.SendEmail(sender,to,htmlBody,"Email sending with .NETCore","Mustafa Ulas Blog"); 

 

                      if (result.IsCompleted)
        { 

 

                                  Console.WriteLine("Email has sended");
            Console.ReadLine(); 

 

             }

 

        } 

 

 }


   

    Finally, the email output will be like this. Based on the output here, you can see more clearly what the parameters sent to the method to send an Email do. You can access the source codes of this project here.