Quantcast
Channel: Faisal Pathan – The Code Hubs
Viewing all articles
Browse latest Browse all 10

How To Send Email Using MailKit In MVC

$
0
0

Introduction

In this article, We will learn how to send email using MailKit in MVC.

Simple Mail Transfer Protocol (SMTP) is a TCP/IP protocol for used in sending and receiving e-mail. Most e-mail systems that send mail over the Internet use SMTP to send messages from one server to another.

below list of SMTP Server and Port Numbers:

No Server Host Port
1 Gmail smtp.gmail.com 587
2 Yahoo Mail smtp.mail.yahoo.com 465
3 Hotmail smtp.live.com 465
4 Office365.com smtp.office365.com 587
5 Outlook smtp.live.com 587
6 Zoho Mail smtp.zoho.com 465
7 Yahoo Mail Plus plus.smtp.mail.yahoo.com 465

Install Package

MailKit

MailKit is a library for used to sending email.

Send Email

Let’s Begin

Creating a new MVC Project and install the MailKit library from Manage NuGet packages.

After the add new HomeController in your project and below code in it.

       [HttpPost]
        public async Task<JsonResult> SendEmailUsingMimeKit(string toEmail)
        {
            try
            {
                string emailBarcodeA = string.Empty;
                string emailBarcodeB = string.Empty;
                EmailMessage message = new EmailMessage
                {
                    Sender = new MailboxAddress("Email Send - MailKit", "your email address"),
                    Reciever = new MailboxAddress("Email Send - MailKit", ""),
                    Subject = "Test Message",
                    Content = "Hello",
                };
                var mimeMessage = CreateMimeMessageFromEmailMessage(message, toEmail, emailBarcodeA, emailBarcodeB);
                using (SmtpClient smtpClient = new SmtpClient())
                {
                    smtpClient.Connect("smtp.gmail.com", 465, true);
                    await smtpClient.AuthenticateAsync("your email address, "your password");
                    await smtpClient.SendAsync(mimeMessage);
                    await smtpClient.DisconnectAsync(true);
                }
                return Json(new { IsSuccess = true, Message = "Email successfully send." }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }

        }
        private MimeMessage CreateMimeMessageFromEmailMessage(EmailMessage message, string emailBarcode, string emailBarcodeA, string emailBarcodeB)
        {
            try
            {
                var emailBarcodeMail = new MailboxAddress("Email Barcode", emailBarcode);
                var emailBarcodeMailA = new MailboxAddress("CC", "");
                var emailBarcodeMailB = new MailboxAddress("CC", "");
                var mimeMessage = new MimeMessage();
                mimeMessage.From.Add(message.Sender);
                mimeMessage.To.Add(emailBarcodeMail);
                if (!string.IsNullOrEmpty(emailBarcodeA))
                {
                    emailBarcodeMailA = new MailboxAddress("CC", emailBarcodeA);
                    mimeMessage.To.Add(emailBarcodeMailA);
                }

                if (!string.IsNullOrEmpty(emailBarcodeB))
                {
                    emailBarcodeMailB = new MailboxAddress("CC", emailBarcodeB);
                    mimeMessage.To.Add(emailBarcodeMailB);
                }
                var builder = new BodyBuilder();
                builder.HtmlBody = message.Content;
                if (!string.IsNullOrEmpty(message.AttachmentPath))
                {
                    string fileName = message.AttachmentPath;
                    builder.Attachments.Add(fileName, message.Attachment);
                }
                mimeMessage.Subject = message.Subject;
                //mimeMessage.Body = new TextPart(MimeKit.Text.TextFormat.Html);
                mimeMessage.Body = builder.ToMessageBody();
                // { Text = message.Content };
                return mimeMessage;
            }
            catch (Exception ex)
            {

                throw;
            }
        }

and After Create view Index.cshtml and below code in it.

<div class="">
    <div class="col-md-12">
        <input type="text" class="form-control" id="txtEmail" placeholder="Enter Email Address" /><br/>
        <button type="button" class="btn btn-success mt-2 ml-2" onclick="SendEmail()">Send Email</button>
    </div>
</div>

<script>
    function SendEmail() {
        $.ajax({
            url: "/Home/SendEmailUsingMimeKit",
            data: { "toEmail": $('#txtEmail').val() },
            type:"POST",
            success: function (result) {
                alert(result.Message);
            },
            error: function (err) {
                alert(err);
            }
        })
    }
</script>

Let’s run the application and click to Send Email button.

Output :

Thank you for reading. If you have any doubt please let me know.

Read my previous blogs here.

The post How To Send Email Using MailKit In MVC appeared first on The Code Hubs.


Viewing all articles
Browse latest Browse all 10

Trending Articles