Sending Email using smtp || Mailkit in ASP.Net




HOW TO SEND EMAIL USING SMTP || MAILKIT IN ASP.NET WEBFORMS, ASP.NET Core USING C#

If we need your application to send email to specific mail id, either for Login confirmation or any other purpose. You can use .NET namespace “system.web.mail” which allows users to send smtp mails. SMTP runs on port no 25 is  the default port, but it may vary different Mail Servers .

What is SMTP ?
SMTP (simple mail transfer protocol) is an electronic standard for email transmission. When you receive an email in your inbox, most likely it is being sent from an SMTP.
Below are a few good SMTP alternatives which you might want to look into.
§  SparkPost (free up to 100,000 emails per month)
§  Mailgun (free up to 10,000 emails per month)
§  Mailjet (free up to 6,000 emails per month)
§  SendGrid



Sending mail in ASP.NET (C#)

using System;
using System.Windows.Forms;
using System.Net.Mail;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

 private void button1_Click(object sender, EventArgs e)
        {
            try
            {
          MailMessage mail = new MailMessage(); //creating an object(mail)   for this MailMessage class

                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.Subject = "Test Mail";
                mail.Body = "--Put the content for your mail here--";

                mail.From = new MailAddress("Sending_Email_Address@gmail.com");
                mail.To.Add("DestinationEmailID@gmail.com");
                
                SmtpServer.Port = 587; //port no

//using NetworkCredential for password based authentication.
 
                  SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password"); //gmail username and password

                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                MessageBox.Show("Mail has been Sent ");
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}









Sending mail with attachment

For sending attachment we must add library: System.Net.Mail.Attachment attachment;
//attachment = new System.Net.Mail.Attachment("your attachment file");
//mail.Attachments.Add(attachment);


//button click function for email sending with attachment

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.Subject = "Test Mail - 1";
                mail.Body = "Sending mail with attachment";
 
                mail.From = new MailAddress("Sending_Email_Address@gmail.com");
                mail.To.Add("DestinationEmailID@gmail.com");
 
                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment("put your attachment file here");
                mail.Attachments.Add(attachment);
 
                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");//gmail username and password
                SmtpServer.EnableSsl = true;
 
                SmtpServer.Send(mail);
                MessageBox.Show("Mail has been Sent");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }




//Now you will definitely get email with confirmation link

 


//sending email in asp.net core

First install package MailKit and then go through code below:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MimeKit;
using System.Net.Mail;
using SendMailApp.Models;
using MailKit.Net.Smtp;

namespace SendMailApp.Controllers
{
    public class HomeController : Controller
    {

//Action for Sending mail

        public IActionResult Index()
        {
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("UserName","Email@gmail.com"));
            message.To.Add(new MailboxAddress("DestinationName", "email@gmail.com"));
            message.Body = new TextPart("plain")
            {
                Text = "Put content for the Email";
            };

            using (var emailClient = new MailKit.Net.Smtp.SmtpClient())
            {
                emailClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
                emailClient.Connect("smtp.gmail.com", 587, false);

                emailClient.Authenticate("sendingEmail@gmail.com","Password");


                emailClient.Send(message);
                emailClient.Disconnect(true);
            }

                return View();
        }
    }
}



 Example:

Here is an example in asp.net core with angular5, for sending confirmation mail to any user entered in a textbox.

using CoreWithAngular5.Models;
using MailKit.Security;
using Microsoft.AspNetCore.Mvc;
using MimeKit;

namespace CoreWithAngular5.Controllers
{
    [Produces("application/json")]
    public class InviteUserController : Controller
    {
       
        [Route("api/inviteUser")]
        public ActionResult InviteUser([FromBody] InviteByEmailModel email) // InviteByEmailModel is model name with string Email.
        {
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("sender’s user name", "sender’s email"));
            message.To.Add(new MailboxAddress("Admin",email.Email));
message.Subject = "Admin Inviation to System";
            message.Body = new TextPart("plain")
            {
                Text = "Dear Admin," +
                "You are invited to setup the system.Your username: suman, Password: suman." +
                "Click this link for login http://localhost:53795/sign-in"
            };

            using (var emailClient = new MailKit.Net.Smtp.SmtpClient())
            {
                emailClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
                emailClient.Connect("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);

                emailClient.Authenticate("YourMail", "YourPassword");

                emailClient.Send(message);
                emailClient.Disconnect(true);
            }

            return Ok();
        }
    }
}


Click here for More

Comments