Thursday, 27 November 2014

MVC 4 Razor: Send Email with multiple attachments in ASP.NET using C#

Hi friends,in this article I will explain about How to Send Email with multiple attachments in ASP.NET  MVC 4 Razor:
For sending mail from ASP.NET MVC we use the "System.Net.Mail" namespace. Let's explain how to do this.
I already explained in the previous articles about MVC 4: How to bind dropdownlist inside WebGrid in MVC 4 Razor using C# ,Create/Generat PDF with image Using RazorPDF in ASP.Net MVC and MVC4: Show Multiple Models in a Single View using dynamically created object.
Model(SendMail.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MvcSendEmailWithAttachment.Models
{
    public class SendMail
    {
        [Display(Name = "First Address")]
        [Required(ErrorMessage = "First Address is Required")]
        public string FromMailID { get; set; }
        [Display(Name = "Password")]
        [Required(ErrorMessage = "Password is Required")]
        public string password { get; set; }
        [Display(Name = "To mail ID")]
        [Required(ErrorMessage = "To mail ID is Required")]
        public string To { get; set; }
        [Display(Name = "Subject")]
        [Required(ErrorMessage = "Subject is Required")]
        public string Subject { get; set; }
        [Display(Name = "Mail Body")]
        [Required(ErrorMessage = "Mail Body is Required")]
        public string Body { get; set; }
    }
}

Controller(SendMailController.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcSendEmailWithAttachment.Models;
using System.Net.Mail;
using System.IO;
using System.Net;

namespace MvcSendEmailWithAttachment.Controllers
{
    public class SendMailController : Controller
    {
        public ActionResult SendMail()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SendMail(SendMail objSendMail, HttpPostedFileBase uploadedFile1, HttpPostedFileBase uploadedFile2, HttpPostedFileBase uploadedFile3)
        {
            if (ModelState.IsValid)
            {

                MailMessage mail_mes = new MailMessage();

                mail_mes.To.Add(objSendMail.To);
                mail_mes.From = new MailAddress(objSendMail.FromMailID);
                mail_mes.Subject = objSendMail.Subject;
                mail_mes.Body = objSendMail.Body;
                mail_mes.IsBodyHtml = false;

                if (uploadedFile1 != null)
                {
                    string fileName = Path.GetFileName(uploadedFile1.FileName);
                    mail_mes.Attachments.Add(new Attachment(uploadedFile1.InputStream, fileName));
                }
                if (uploadedFile2 != null)
                {
                    string fileName = Path.GetFileName(uploadedFile2.FileName);
                    mail_mes.Attachments.Add(new Attachment(uploadedFile2.InputStream, fileName));
                }
                if (uploadedFile3 != null)
                {
                    string fileName = Path.GetFileName(uploadedFile3.FileName);
                    mail_mes.Attachments.Add(new Attachment(uploadedFile3.InputStream, fileName));
                }
                SmtpClient smtp = new SmtpClient("smtp.gmail.com",587);
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                NetworkCredential networkCredential = new NetworkCredential(objSendMail.FromMailID,objSendMail.FromMailID,objSendMail.password);//Or your Smtp Email ID and Password
                smtp.EnableSsl = true;
                smtp.Credentials = networkCredential;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = networkCredential;
                try
                {
                    smtp.Send(mail_mes);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                ViewBag.Message = "Sent";
                return View("SendMail");
            }
            else
            {
                return View();
            }
        }
    }
}

View(SendMail.cshtml):
@model MvcSendEmailWithAttachment.Models.SendMail
@{
    ViewBag.Title = "SendMail with Multiple attachments";
}

<h2>SendMail</h2>
<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        if ('@ViewBag.Message' == 'Sent') {
            alert('Mail has been sent successfully');
        }
    });
</script>
<style type="text/css">
.validation-summary-errors
{
    color: #C10084;
    font-size: medium;
    font-family:Tahoma;
}
</style>

<fieldset>
    <legend>Send Email with multiple attachments
    </legend>
    @using (@Html.BeginForm("SendMail", "SendMail", FormMethod.Post, new { @id = "form1", @enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary()
        <table>
         <tr>
                <td>From mail ID:
                </td>
                <td>
                    @Html.TextBoxFor(m => m.FromMailID)
                </td>
            </tr>
             <tr>
                <td>Password:
                </td>
                <td>
                    @Html.PasswordFor(m => m.password)
                </td>
            </tr>
            <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 1
                </td>
                <td>
                    <input type="file" name="fileUploader1" />
                </td>
            </tr>
              <tr>
                <td>Attachment 2
                </td>
                <td>
                    <input type="file" name="fileUploader2" />
                </td>
            </tr>
              <tr>
                <td>Attachment 3
                </td>
                <td>
                    <input type="file" name="fileUploader3" />
                </td>
            </tr>
            <tr>
                <td>Body:
                </td>
                <td>
                    @Html.TextAreaFor(m => m.Body)
                </td>
            </tr>
        </table>   
          <input type="submit" value="Send Mail" />
    }
</fieldset>


The output of the above code as shown in the below figure.When you don't enter values and click on Send Mail button then  validations messages will show.

Enter the values and click on Send Mail then mail will be sent.

You can download the code by clicking on the below Download image. 

No comments:

Post a Comment

© 2012-2014 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.