ttmind

Main Navigation

ttmind
  • jim-jams
  • Tech
  • Positive
Login

Login

Facebook Google

OR

Remember me Forgot password?

Don't have account? Signup here.

Sort by Categorys

.Net

PHP

Java

JavaScript

Database

Server

Client Side

Tools

Artificial Intelligence

Cloud

Hybrid Development

Event

Smart City

Education

Security

Scrum

Digital Marketing

APP Development

Business

Internet

Simulation

Art

Network

Microservices

Architecture

Technology

Leadership

    Top Articles

  • How Does Social Media Bring People Together?
    TTMind Author
  • How to read appSettings JSON from Class Library in ASP.NET Core
    Anil Shrestha
  • Printing Support In Asp.Net Core
    TTMind Author
  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
    Prakash Pokhrel
  • Images Upload REST API using ASP.NET Core
    Prakash Pokhrel
  • Related Topic

  • How to read appSettings JSON from Class Library in ASP.NET Core
  • Printing Support In Asp.Net Core
  • Images Upload REST API using ASP.NET Core
  • How to use IActionFilter, IAsyncActionFilter in ASP.NET Core MVC?
  • ASP.NET CORE - Blazor CRUD operation using ADO.NET
  • Tech
  • About Us
  • Contact Us
  • TechHelp
  • PositiveHelp
  • Jim-Jams Help
  • Terms & Conditions

© Copyright ttmind.com

Main Content

How to send the Email from Aspnet core?

.Net .Net Core about 6 years ago || 9/24/2019 || 4.4 K View

  • Hide

Most of my project need common feature Sending Mail.  In this article, we will learn how to send an email to given an email. We are using Mailkit that is available in  NuGet. It is very simple. I am using Gmail SMTP.

  • Create the new web project on Visual studio.
  • Add Mailkit and MimeKit From Nuget.

Mailkit

MailKit is a cross-platform mail client library built on top of MimeKit.

How to Add Mailkit in our project.

Creating a project in visual studio.  Right-click on your project name and choose Manage Nuget Packages. And click on Browse. Type MailKit and install it. MimeKit also.

In the second we need to set the SMPT.

public class SMTPAuthProvider
    {
        public static string SMTPServerAddress = "smtp.gmail.com";
        public static int SMTPPort = 465;
        public static bool SMTPUsesSSL = true;
        public static string SMTPUserName = "yourgmail@gmail.com";
        public static string SMTPPassword = "yourpassword";
    }

 

Note:

  • For Gmail you need set up your email address.

  • Trun off the 2-Step Verification if you enable

  • Trun on Less secure app access.

 https://myaccount.google.com/signinoptions/two-step-verification click this to change 2-step verification.

https://myaccount.google.com/lesssecureapps click this to change less secure apps

Now write some method which can send mail to the desired email address.  In the below code there are two methods one sync method and another one is the async method. We need both in the real project. just Copy the code below and paste in where you want.

public class EmailHelpers
    {
        public void SendEmail(string emailSubject, string fromName,
            string toName, string toEmailID, string stmMessage)
        {
            BodyBuilder bodyBuilder = new BodyBuilder();
            bodyBuilder.HtmlBody = stmMessage;
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(fromName, SMTPAuthProvider.SMTPUserName));
            message.To.Add(new MailboxAddress(toName, toEmailID));
            message.Subject = emailSubject;
            message.Body = bodyBuilder.ToMessageBody();
            using (var client = new SmtpClient())
            {
                client.Connect(SMTPAuthProvider.SMTPServerAddress, 
                    SMTPAuthProvider.SMTPPort, 
                    SMTPAuthProvider.SMTPUsesSSL);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                // Note: since we don't have an OAuth2 token, disable 	
                // the XOAUTH2 authentication mechanism.     
                client.Authenticate(SMTPAuthProvider.SMTPUserName, SMTPAuthProvider.SMTPPassword);
                client.Send(message);
                client.Disconnect(true);
            }
        }
        public async Task SendEmailAsync(string emailSubject, string fromName,
            string toName, string toEmailID, string stmMessage)
        {
            BodyBuilder bodyBuilder = new BodyBuilder();
            bodyBuilder.HtmlBody = stmMessage;
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(fromName, SMTPAuthProvider.SMTPUserName));
            message.To.Add(new MailboxAddress(toName, toEmailID));
            message.Subject = emailSubject;
            message.Body = bodyBuilder.ToMessageBody();
            using (var client = new SmtpClient())
            {
                await client.ConnectAsync(SMTPAuthProvider.SMTPServerAddress, 
                                          SMTPAuthProvider.SMTPPort, 
                                          SecureSocketOptions.SslOnConnect)
                                          .ConfigureAwait(false);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                await client.AuthenticateAsync(SMTPAuthProvider.SMTPUserName, 
                SMTPAuthProvider.SMTPPassword);
                await client.SendAsync(message).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
    }

Make sure you using the Name like below on your class.

using MimeKit;
using MailKit.Net.Smtp;
using MailKit.Security;

Calling for this method. I'm too lazy to make another function. So, I just called this function from homeController.

public IActionResult Index()
        {
            new EmailHelpers().SendEmail(
                "Send Mail article",
                "Anil Shrestha",
                "In ttmind", 
                "anilshrestha910@outlook.com", 
                "This your Body Message you can set here"
                );
            return View();
        }

Here is the output. 

 That's the way we sending the email from aspnet core. That's it keep coding. 

Read More:

  • How to become .Net Developer
  • read appSettings JSON from Class Library in ASP.NET Core
  • CRUD Operation in ASP.NET Core MVC with ADO.NET

  • 1
  • 0
  • 0
    • Facebook
    • Twitter
    • Google +
    • LinkedIn

About author

Anil Shrestha

Anil Shrestha

Qualified and skilled professional with experience working as a Software Developer

Reset Your Password
Enter your email address that you used to register. We'll send you an email with your username and a link to reset your password.

Quick Survey