Sending Email's from a web-application is necessary nowadays, and thank god we have an easy solution for it using C# ASP.NET MVC.So, In this article, I have explained step by step how you can send email in C# (ASP.NET MVC) application with attachment, we will create example of sending Email using Contact form.

We will be sending Email using "System.Net.Mail" and will be sent via SMTP (Simple Mail Transfer Protocol). There are many other ways to send an email - POP3, IMAP, Exchange Web Services, Outlook Interop and so on, but we will not be covering all these here.

c-send-email-with-attachment-asp-net-mvc-example-min.png

1.Create a Model

Add a class in your Models folder with name it, EmailModal.cs with this code

public class EmailModel
{
       //Email Sender Name
        [Required, Display(Name="Your name")]        
        public string FromName { get; set; }

        //Email Sender Email id
        [Required, Display(Name = "Your email"), EmailAddress]
        public string FromEmail {get;set;}

        // Message body
        [Required]
        public string Message { get; set; }
}

2. Create a Razor View for user to enter details in your form

Now create a .cshtml page for user to fill the form, and submit it in back end, lt's name your page as Contact , so in Controller generate an ActionResult method

public ActionResult Contact()
{
 return View();
}

After this generate a razor code for  Contact.cshtml page

@model MVCEmail.Models.EmailModel
@{
    ViewBag.Title = "Contact";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <h4>Send your comments.</h4>
    <hr />
    <div class="form-group">
        @Html.LabelFor(m => m.FromName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.FromName, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.FromName)
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.FromEmail, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.FromEmail, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.FromEmail)
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Message, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextAreaFor(m => m.Message, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.Message)
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Send" />
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Note: You should always validate and verify email address in C# before sending mail.

3. Save the form details in database and send Email

Now, this is the important part, in which we need to collect the form data in back end using C# and send Email, so we can have code

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Contact(EmailFormModel model)
{
    if (ModelState.IsValid)
    {
      using(var context = new DbConnection())
      {
        // Save data in database
      }
      //Send Email
      MailMessage Msg = new MailMessage();
      Msg.From = new MailAddress("senderEmailId@gmail.com","Sender Name");// replace with valid value
      Msg.Subject = "Contact";
      Msg.To.Add("Emailto@gmail.com"); //replace with correct values
      Msg.Body = Model.Message;
      Msg.IsBodyHtml = true;
      Msg.Priority = MailPriority.High;
      SmtpClient smtp = new SmtpClient();
      smtp.Host = "smtp.gmail.com";
      smtp.Port = 587;
      smtp.Credentials = new System.Net.NetworkCredential("senderEmailId@gmail.com", "password");// replace with valid value
      smtp.EnableSsl = true;
      smtp.Timeout = 20000;

      smtp.Send(Msg);
     return RedirectToAction("Sent");
    }
    return View(model);
}

4. Redirect to Message Sent page

public ActionResult Sent()
{
    return View();
}

generate its view and paste this code in it

@{
    ViewBag.Title = "Sent";
}
<h2>Your message has been sent</h2>

That's it, you are done.

You start by creating a MailMessage object. MailMessage is the class that represents an email to be sent. Recipients are represented as a collection of MailAddress objects. They are added to the To property of the MailAddress class. The sender is also represented as an instance of the MailAddress class and is assigned to the message's From property. The Subject and Body properties are self-explanatory. By default, email messages are created as plain text. If you want to send an HTML email, you pass HTML to the Body property (as in this example) and then explicitly set the IsBodyHtml property to true.

Once the message has been created, it needs sending. The SmtpClient class is responsible for that task. The configuration of the SmtpClient object is often the place where most email sending errors occur, so it is important to ensure that you use the right settings. They are almost identical for both Outlook and Gmail:

When you set EnableSsl to true, you actually switch TLS on, which is required for port 587. Https is not supported by the SmtpClient object. For more details, read the Remarks section of the docs on MSDN.

5. Adding attachment's

First of all go back to your EmailModel.cs and add a field  public HttpPostedFileBase Upload { get; set; } , and add it in View using code below

<div class="form-group">
        @Html.LabelFor(m => m.Upload, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            <input type="file" name="upload" />
        </div>
    </div>

now you need to change your form type in view to 

Html.BeginForm("Contact", "Home", null, FormMethod.Post, new {enctype = "multipart/form-data"})

in controller, your new code will look like 

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Contact(EmailFormModel model)
{
    if (ModelState.IsValid)
    {
      using(var context = new DbConnection())
      {
        // Save data in database
      }
      //Send Email
      MailMessage Msg = new MailMessage();
      Msg.From = new MailAddress("senderEmailId@gmail.com","Sender Name");// replace with valid value
      Msg.Subject = "Contact";
      Msg.To.Add("Emailto@gmail.com"); //replace with correct values
      Msg.Body; 
 //New Code to upload
      if (Model.Upload != null)
      {
       string fileName = Path.GetFileName(Model.Upload.FileName);
       Msg.Attachments.Add(new Attachment(Model.Upload.InputStream, fileName));
      };

      Msg.Body = Model.Message;
      Msg.IsBodyHtml = true;
      Msg.Priority = MailPriority.High;
      SmtpClient smtp = new SmtpClient();
      smtp.Host = "smtp.gmail.com";
      smtp.Port = 587;
      smtp.Credentials = new System.Net.NetworkCredential("senderEmailId@gmail.com", "password");// replace with valid value
      smtp.EnableSsl = true;
      smtp.Timeout = 20000;

      smtp.Send(Msg);
     return RedirectToAction("Sent");
    }
    return View(model);
}

You can place your smtp details in web.config also