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.
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;
using
System.Net;
using
System.Net.Mail;
namespace
MailSending.Controllers
{
public
class
EmailController
: Controller
{
//
//
GET: /Email/
public
ActionResult
Form()
{
return
View();
}
[HttpPost]
public
ActionResult
Form(string
receiverEmail, string
subject, string
Message)
{
try
{
if
(ModelState.IsValid)
{
var
senderemail = new
MailAddress("WriteYourSenderGmail",
"Demo
Test");
var
receivermail = new
MailAddress(receiverEmail,
"Receiver");
var
password = "WriteYourSenderPassword";
var
sub = subject;
var
body = Message;
var
smtp = new
SmtpClient
{
Host
= "smtp.gmail.com",
Port
= 587,
EnableSsl
= true,
DeliveryMethod
= SmtpDeliveryMethod.Network,
UseDefaultCredentials
= false,
Credentials
= new
NetworkCredential(senderemail.Address,
password)
};
using
(var
mes = new
MailMessage(senderemail
, receivermail)
{
Subject
= subject,
Body
= body
}
)
{
smtp.Send(mes);
}
return
View();
}
}
catch
(Exception)
{
ViewBag.Error
= "Oops
! Problem in sending email";
}
return
View();
}
}
}
=============================================================================================
Right Click on Controller => Add View => FormView
@{
ViewBag.Title
= "Form";
}
@if
(ViewBag.Error != null)
{
<h2>@ViewBag.Error</h2>
}
<div
class="container">
<form
method="post"
action="Email/Form"
form-control-static">
Receiver
Email:</span>
<input
class="form-control"
type="text"
name="receiverEmail"
/><br
/>
<span
class="form-control-static">Subject:</span>
<input
class="form-control"
type="text"
name="Subject"
/><br
/>
<span
class="form-control-static">Message:</span>
<textarea
class="form-control"
cols="8"
rows="6"
name="Message"></textarea><br
/>
<button
class="btn-btn-primary"
type="submit">Send
Email</button>
</form>
</div>
==============================================================================================
Route Config file :
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;
using
System.Web.Routing;
namespace
MailSending
{
public
class
RouteConfig
{
public
static
void
RegisterRoutes(RouteCollection
routes)
{
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


No comments:
Post a Comment