Monday, December 11, 2017

How to send email with attachment using Gmail SMTP from asp.net MVC application

In this article I am going to explain how to send email with attachment using Gmail SMTP from asp.net MVC application.

Description:
I want to send email with attachment using Gmail account.

Implementation:
Open the web.config file of project. Set key in Appsettings. After that mailsettings as shown below:
<appSettings>
    <add key="Email" value="Emailaddress@gmail.com"/>
  </appSettings>
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network enableSsl="true" port="587" host="smtp.gmail.com" userName=" Emailaddress@gmail.com" password="password"/>
      </smtp>
    </mailSettings>
  </system.net>

 Add Controller
Add empty controller to project. Create an ActionResult to send email.

Complete code of Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2017.Models;
using System.Security.Cryptography;
using System.Configuration;
using System.Net.Mail;
using System.Net;
using System.IO;
namespace mvcapplication2017.Controllers
{
  
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        DemoEntities db = new DemoEntities();
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult SendEmail()
        {
            return View();
        }
        [HttpPost]
        public ActionResult SendEmail(string Name, string Subject,string EmailID, string message,HttpPostedFileBase file1)
        {
            if (ModelState.IsValid)
            {
                string Email = ConfigurationManager.AppSettings["Email"].ToString();
                string Emailto = EmailID;
                MailMessage mail = new MailMessage(Email, Emailto);
                mail.Subject = Subject;
                string mailmessage = "Name :"+ Name +"<br>"+ message;
                mail.Body = mailmessage;
                mail.IsBodyHtml = true;
                if (file1 != null && file1.ContentLength > 0) 
                {
                    string fileName = string.Format("{0}/{1}", Server.MapPath("~/images/"), Path.GetFileName(file1.FileName));
                    file1.SaveAs(fileName);
                    mail.Attachments.Add(new Attachment(fileName));
                }
                SmtpClient smtp = new SmtpClient();
                smtp.Send(mail);
                ViewBag.Message = "Email sent successfully";
            }
            return View();
        }
    }
}

  
Add view:
Add new view for SendEmail Actionresult.

Source code of View:


@{
    ViewBag.Title = "Send Email";
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<h2>Send Email</h2>
@using (Html.BeginForm("SendEmail", "Login", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary()
<fieldset>
    <legend>Send Email</legend>
    <table>
        <tr>
            <td>Name :</td>
            <td>@Html.TextBox("Name", "", new { @data_val = "true", @data_val_required = "Please enter name",placeholder="Name"})</td>
        </tr>
        <tr>
            <td>Email :</td>
            <td>@Html.TextBox("EmailID","", new { @data_val = "true",@data_val_email="email dsfdsfsdf", @data_val_required = "Please enter email address",placeholder="Email" })</td>
        </tr>
        <tr>
            <td>Subject :</td>
            <td>@Html.TextBox("Subject", "", new { @data_val = "true", @data_val_required = "Please enter subject", placeholder = "Subject" })</td>
        </tr>
        <tr>
            <td>Message :</td>
            <td>@Html.TextArea("message", "", new { rows = "6", cols = "22", @data_val = "true", @data_val_required = "Please enter message", placeholder = "Message" })</td>
        </tr>
        <tr>
            <td>Attachment :</td>
            <td><input id="File1" name="File1" type="file" /></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Send Email" /></td>
        </tr>
    </table>
    @ViewBag.Message
</fieldset>
}
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>



No comments:

Post a Comment