In this article I am going to explain how to send email from
asp.net MVC application using web.config
.
Description:
If you don’t have SMTP server to send email then you can use
Gmail smtp server to send email from your MVC application. To send email from web.config
file you have to set appsetting.
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 an empty controller to project. Create an Actionresult
to send email.
Complete code to Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mvctest2017.Models;
using System.Security.Cryptography;
using System.Configuration;
using System.Net.Mail;
using System.Net;
namespace mvctest2017.Controllers
{
public class SendemailController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult SendEmail()
{
return View();
}
[HttpPost]
public ActionResult SendEmail(string Name, string Subject,string EmailID, string message)
{
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;
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
ViewBag.Message = "Email sent
successfully";
}
return View();
}
}
}
Add
view
Add view for Send email Actionresult.
Complete 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())
{
@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 = "Enter
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" })</td>
</tr>
<tr>
<td>Subject :</td>
<td>@Html.TextBox("Subject", "", new { @data_val = "true", @data_val_required
= "Please enter 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" })</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