ASP.NET MVC

Sending A Mail Using ASP.NET MVC

Here, in this article, we will discuss how we can send mail using ASP.NET MVC 5. Sending mail is nowadays one of the key features of any application. Here we will see to send mail using SMTP server with attachments and HTML body.

Now, Let’s begin it.

First, create a new project in ASP.NET MVC

Now, create a class which will handle our mail message.
Goto Models -> Create a class as Message

public class Message
    {
        public string To { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
    }

Now, go to View -> Home -> Index.cshtml and replace the file with this code

@model EmailDemo.Models.Message

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Mail Demo</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <style>
        body {
            background: -webkit-linear-gradient(left, #0072ff, #00c6ff);
        }

        .contact-form {
            background: #fff;
            margin-top: 10%;
            margin-bottom: 5%;
            width: 70%;
        }

            .contact-form .form-control {
                border-radius: 1rem;
            }

        .contact-form form {
            padding: 14%;
        }

            .contact-form form .row {
                margin-bottom: -7%;
            }

        .contact-form h3 {
            margin-bottom: 8%;
            margin-top: -10%;
            text-align: center;
            color: #0062cc;
        }

        .contact-form .btnContact {
            width: 50%;
            border: none;
            border-radius: 1rem;
            padding: 1.5%;
            background: #dc3545;
            font-weight: 600;
            color: #fff;
            cursor: pointer;
        }

        .btnContactSubmit {
            width: 50%;
            border-radius: 1rem;
            padding: 1.5%;
            color: #fff;
            background-color: #0062cc;
            border: none;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container contact-form">
        <form method="post" enctype="multipart/form-data">
            <h3>Drop Us a Message</h3>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        @Html.TextBoxFor(m => m.To, new { @class="form-control",@placeholder="Message To" })
                    </div>
                    <div class="form-group">
                        @Html.TextBoxFor(m => m.Subject, new { @class = "form-control", @placeholder = "Subject" })
                    </div>
                    <div class="form-group">
                        <input type="file" class="form-control" name="files" multiple="multiple" />
                    </div>
                    <div class="form-group">
                        <input type="submit" name="btnSubmit" class="btnContact" value="Send Message" />
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        @Html.TextAreaFor(m => m.Body, new { @rows = 6, @cols = 50, @class = "form-control", @placeholder = "Body" })
                    </div>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

Now we will add the new folder for storing our email template.

Left click on the project -> Add -> New Folder and name it as Template

Insert new EmailPage.html file in it and replace the code with following.

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="x-apple-disable-message-reformatting">
    <title>Welcome Message</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <div class="table-responsive">
            <table class="table">
                <tr>
                    <th colspan="2" class="text-center">Welcome Message</th>
                </tr>
                <tr>
                    <td>Message</td>
                    <td>{message}</td>
                </tr>
            </table>
        </div>
    </div>
</body>
</html>

Now open Web.Config file present at root directory of the project and add few keys

<appSettings>
    <add key="EmailId" value="your-email-id" />
    <add key="EmailPassword" value="your-email-password" />
</appSettings>

Now finally we will code the controller login

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Web.Services.Description;

namespace EmailDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(Models.Message model, List<HttpPostedFileBase> files)
        {
            string EmailId = ConfigurationManager.AppSettings["EmailId"];
            string EmailPassword = ConfigurationManager.AppSettings["EmailPassword"];
            try
            {
                using (MailMessage mail = new MailMessage(EmailId, model.To))
                {
                    mail.Subject = model.Subject;
                    mail.Body = PopulateBody(model.Body);
                    foreach (HttpPostedFileBase file in files)
                    {
                        if (file != null)
                        {
                            string fileName = Path.GetFileName(file.FileName);
                            mail.Attachments.Add(new Attachment(file.InputStream, fileName));
                        }
                    }
                    mail.IsBodyHtml = true;
                    SmtpClient smtp = new SmtpClient
                    {
                        Host = "smtp.gmail.com",
                        EnableSsl = true,
                        Port = 587
                    };
                    NetworkCredential networkCredential = new NetworkCredential(EmailId, EmailPassword);
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = networkCredential;
                    smtp.Port = 587;
                    smtp.Send(mail);
                }
            }
            catch (Exception ex)
            {
                MailLog(ex);
            }
            return View();
        }

        private string PopulateBody(string message)
        {
            string body = string.Empty;
            using (StreamReader reader = new StreamReader(Server.MapPath("~/Template/EmailPage.html")))
            {
                body = reader.ReadToEnd();
            }
            body = body.Replace("{message}", message);
            return body;
        }
        public static void MailLog(Exception ex)
        {
            string lines = "Error occured at " + DateTime.Now.ToString("MM/dd/yyyy h:mm tt") + "\r\n";
            lines += "****************************************************************** \r\n";
            lines += "StackTrace: " + ex.StackTrace?.ToString() + " \r\n";
            lines += "ErrorMessage: " + ex.Message?.ToString() + " \r\n";
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Mail Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\Mail Logs\\" + "MailLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + "_" + DateTime.Now.Ticks.ToString() + ".txt";
            if (!System.IO.File.Exists(filePath))
            {
                using (StreamWriter sw = System.IO.File.CreateText(filePath))
                {
                    sw.WriteLine(lines);
                }
            }
            else
            {
                using (StreamWriter sw = System.IO.File.AppendText(filePath))
                {
                    sw.WriteLine(lines);
                }
            }
        }
    }
}

Output:

You can download the source code from here

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

Share
Published by
Faisal Pathan

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago