Email sending code with an attachment using ASP.NET MVC

Please follow the below steps;

Step-1: Create a new model class in models folder

The following is the code for new model;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVC_SentMailApp.Models
{
    public class MailModel
    {
        public string To { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
    }
}
Step-2: Create a new controller in Controllers Folder
Following is the code for Controller;
SentMailController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
namespace MVC_SentMailApp.Controllers
{
    public class SentMailController : Controller
    {
        //
        // GET: /Sent Mail/
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// Send Mail with Gmail
        /// </summary>
        /// <param name=”objModelMail”>MailModel Object, keeps all properties</param>
        /// <param name=”fileUploader”>Selected file data, example-filename,content,content type(file type- .txt,.png etc.),length etc.</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(SendMailwithAttachment.Models.MailModel objModelMail, HttpPostedFileBasefileUploader)
        {
            if (ModelState.IsValid)
            {
                string from = “Your Gmail Id”; //example:- lakshmi9@gmail.com
                using (MailMessage mail = new MailMessage(from, objModelMail.To))
                {
                    mail.Subject = objModelMail.Subject;
                    mail.Body = objModelMail.Body;
                    if (fileUploader != null)
                    {
                        string fileName = Path.GetFileName(fileUploader.FileName);
                        mail.Attachments.Add(new Attachment(fileUploader.InputStream, fileName));
                    }
                    mail.IsBodyHtml = false;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = “smtp.gmail.com”;
                    smtp.EnableSsl = true;
                    NetworkCredential networkCredential = new NetworkCredential(from, “Your Gmail Password”);
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = networkCredential;
                    smtp.Port = 587;
                    smtp.Send(mail);
                    ViewBag.Message = “Sent”;
                    return View(“Index”, objModelMail);
                }
            }
            else
            {
                return View();
            }
        }
    }
}
Index.cshtml
 
@model MVC_SentMailApp.Models.MailModel
@{
    ViewBag.Title = “Index”;
}
<script src=”~/Scripts/jquery-1.7.1.min.js”></script>
<script>
    $(document).ready(function () {
        if (‘@ViewBag.Message’ == ‘Sent’) {
            alert(‘Mail has been sent successfully’);
        }
    });
</script>
<h2>Index</h2>
<fieldset>
    <legend>Send Email
    </legend>
    @using (@Html.BeginForm(“Index”, “SendMailer”, FormMethod.Post, new { @id = “form1″, @enctype =”multipart/form-data” }))
    {
        @Html.ValidationSummary()
        <input type=”submit” value=”Send” />
        <table>
            <tr>
                <td>To:
                </td>
                <td>
                    @Html.TextBoxFor(m => m.To)
                </td>
            </tr>
            <tr>
                <td>Subject:
                </td>
                <td>
                    @Html.TextBoxFor(m => m.Subject)
                </td>
            </tr>
            <tr>
                <td>Attachment
                </td>
                <td>
                    <input type=”file” name=”fileUploader” />
                </td>
            </tr>
            <tr>
                <td>Body:
                </td>
                <td>
                    @Html.TextAreaFor(m => m.Body)
                </td>
            </tr>
        </table>
    }
</fieldset>
 
In the code above we have the following 4 fields:
  • To
  • Subject
  • Message
  • Attachment

When the user clicks the “Send” button, the mail will be sent to the specified mail address that you provide in the “To” TextBox.

That’s it. Press F5 to run your code.

U can also try it in your local environment — good luck:)

4 Replies to “Email sending code with an attachment using ASP.NET MVC”

  1. Now this is really amazing, how can you people manage to get stuff like this? Man, this is really worth reading and I am going to bookmark your blog for this. Keep updating us.

Leave a Reply

Your email address will not be published. Required fields are marked *