Sunday, November 19, 2017

MVC : Send email using Gmail account

In this article I am going to explain how to send email using Gmail account in MVC.

If you don’t have SMTP server to send email then you can use Gmail smtp server to send email from your MVC application.
Open the web.config file of project. Set key in appsettings. After that mailsettings as shown below:

    <add key="Email" value=""/>
      <smtp deliveryMethod="Network">
        <network enableSsl="true" port="587" host="" userName="" password="password"/>

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();
       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();
                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=""></script>

<h2>Send Email</h2>
@using (Html.BeginForm())
    <legend>Send Email</legend>
            <td>Name :</td>
            <td>@Html.TextBox("Name", "", new { @data_val = "true", @data_val_required = "Please enter name" })</td>
            <td>Email :</td>
            <td>@Html.TextBox("EmailID","", new { @data_val = "true",@data_val_email="email dsfdsfsdf", @data_val_required = "Please enter email address" })</td>
            <td>Subject :</td>
            <td>@Html.TextBox("Subject", "", new { @data_val = "true", @data_val_required = "Please enter subject" })</td>
            <td>Message :</td>
            <td>@Html.TextArea("message", "", new { rows="6", cols="22",@data_val = "true", @data_val_required = "Please enter message" })</td>
            <td><input type="submit" value="Send Email" /></td>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

No comments:

Post a Comment