Send Email using SMTP Server in ASP.Net MVC
File => New Project
Templates => Visual C# => ASP.NET MVC Web Application
Controllers => Add Controller=> EmailController => Add.
File => New Project
Templates => Visual C# => ASP.NET MVC Web Application
Controllers => Add Controller=> EmailController => Add.
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.Mvc;
usingSystem.Net;
usingSystem.Net.Mail;
namespaceMailSending.Controllers
{
publicclassEmailController: Controller
{
//
// GET: /Email/
publicActionResultForm()
{
returnView();
}
[HttpPost]
publicActionResultForm(stringreceiverEmail, stringsubject, stringMessage)
{
try
{
if(ModelState.IsValid)
{
varsenderemail = newMailAddress("WriteYourSenderGmail", "Demo Test");
varreceivermail = newMailAddress(receiverEmail, "Receiver");
varpassword = "WriteYourSenderPassword";
varsub = subject;
varbody = Message;
varsmtp = newSmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = newNetworkCredential(senderemail.Address, password)
};
using(varmes = newMailMessage(senderemail , receivermail)
{
Subject = subject,
Body = body
}
)
{
smtp.Send(mes);
}
returnView();
}
}
catch(Exception)
{
ViewBag.Error = "Oops ! Problem in sending email";
}
returnView();
}
}
}
=============================================================================================
Right Click on Controller => Add View => FormView
@{
ViewBag.Title = "Form";
}
@if(ViewBag.Error != null)
{
h2>@ViewBag.Errorh2>
}
divclass="container">
formmethod="post"action="Email/Form"form-control-static">
Receiver Email:span>
inputclass="form-control"type="text"name="receiverEmail"/>br/>
spanclass="form-control-static">Subject:span>
inputclass="form-control"type="text"name="Subject"/>br/>
spanclass="form-control-static">Message:span>
textareaclass="form-control"cols="8"rows="6"name="Message">textarea>br/>
buttonclass="btn-btn-primary"type="submit">Send Emailbutton>
form>
div>
==============================================================================================
Route Config file :
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.Mvc;
usingSystem.Web.Routing;
namespaceMailSending
{
publicclassRouteConfig
{
publicstaticvoidRegisterRoutes(RouteCollectionroutes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new{ controller = "Email", action = "Form", id = UrlParameter.Optional }
);
}
}
}
=====================================================================
Login to sender gmail
after signed in gmail, open this link
https://www.google.com/settings/security/lesssecureapps
Set Allow less secure apps ON