Tuesday, May 23, 2017

Send Email Using ASP.NET CORE 1.1 With MailKit using VS Code in Ubuntu

In this post I will show you how to Send Email Using ASP.NET CORE 1.1 With MailKit using Visual Studio Code in Ubuntu.

OutPut:




















Install Nuget Package Manager from Extensions
ones it is installed press F1, search for Add Package and select it. then paste NETCore.MailKit and press Enter and continue by pressing Enter.

Some of the SMTP hosts and Port No's are:

Mail Server SMTP Server Port No
Gmail Smtp.gmail.com 587
OutLook Smtp.live.com 587
Yahoo Mail Smtp.mail.yahoo.com 465
Office365.com Smtp.office365.com 587
Hotmail Smtp.live.com 465
Hot Mail Smtp.live.com 465
Use the below namespaces
  

using MimeKit;
using MailKit.Net.Smtp;

Replace Index actionresult with the below code
  

public IActionResult Index()
{
     var msg = sendMail();
     ViewData["Message"] = msg;
     return View();
}

Meathod to send mail
  

public void sendMail()
{
    try
    {
        string From = "fromname@domain.com";                
        string To = "toname@domain.com";
        string Subject = "Sending Email from ASP.NET Core 1.1 With MailKit using VS Code in Ubuntu";
        string Body = "This is a sample body Sending Email from ASP.NET Core 1.1 With MailKit using VS Code in Ubuntu";

        string SmtpServer = "smtp.gmail.com";
        int SmtpPort = 587;

        var mimeMessage = new MimeMessage();
        mimeMessage.From.Add(new MailboxAddress(From));
        mimeMessage.To.Add(new MailboxAddress(To));
        mimeMessage.Subject = Subject;
        mimeMessage.Body = new TextPart("plain")
        {
            Text = Body
        };

        using (var client = new SmtpClient())
        {
            client.Connect(SmtpServer, SmtpPort, false);
            client.Authenticate("fromname@domain.com", "yourpassword");
            client.Send(mimeMessage);                    
            client.Disconnect(true);   
            return "Mail sent succesfully.";                 
        }
    }
    catch (Exception ex)
    {
        string Msg = ex.Message;
        return Msg;
    }
}

No comments:

Post a Comment