How Sent Email Using HtmlMailer Using Asp.net MVC ,Change Password Logic



Configure Gmail For Sent Smtp Mail From Asp.net MVC Using HTML Mailer Template

A)First You Need To Setup Your Mail Provider Credential

1). Goto Www.gmail.com and login it after Login ( you will have to enable less secure sign-ins           under Connected apps & sites. Toggle the switch under “Allow less secure apps” to “ON”.)

2). You will redirect this link 

           https://myaccount.google.com/security#connectedapps

 3). And then select option Directed in red color in the image 



4). Then Goto Settings of gmail

5). navigate to Settings > Outgoing Email. Change the Protocol to SMTP which will 
      open the SMTP Options. As Define In Pic



6).  Use the following settings:
             Server address: smtp.gmail.com
             Server port :465 or 587
             Username:your.email@gmail.com
             Password:your password 
            Connection type:SSL (ssl://) 
       And Setting It Into New File Explain in Next Point 7

7). Then You Will  Add New Cofig file with name Setting.config  And Write This Code

<?xml version="1.0"?>
<appSettings>
<add key="FromEmail" value="your.email@gmail.com" />
  <add key="smtpusername" value="your.email@gmail.com" />
  <add key="smtppassword" value="your password " />
  <add key="smtpport" value="587" />
  <add key="smtphost" value="smtp.dot5hosting.com" />
</appSettings>

8). And Then Finally Add Reference this config File To Root Web.config File Like This

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
 <configSections>
 <\configSections>
<connectionStrings>
<\connectionStrings>
<appSettings configSource="settings.config"/>

</configuration>

9). And Next You Need to Create A Class Which Containt Mail Function For sending Mail From Asp.net MVC
The Mail function Write Under The class into to Utility Sub folder of BAL folder Exist under the Root Directory of Project There Diffrent Function You Can use Any of Them

using System;
using System.Collections;
using System.Configuration;
using System.Net.Mail;
using System.Threading;
using System.Threading.Tasks;
using System.Web;


namespace myProject.BAL.Utility
{
    /// <summary>
    /// Summary description for MailHelper.
    /// </summary>
    public class MailHelper
    {
        #region Methods
        /*testing*/
        public   static  string  SendEmailGmail(string sTo, 
string sFrom, string sCc,
 string sBcc, string sSubject, string sBody)
        {
            string message = string.Empty;
            try
            {
                SmtpClient SmtpMail = new SmtpClient(
Utils.ConfigKey("smtphost"));
                SmtpMail.Port = Utils.ToInt(Utils.ConfigKey("smtpport"));
                SmtpMail.EnableSsl = true;
                SmtpMail.UseDefaultCredentials = true;
                SmtpMail.Credentials = new System.Net.NetworkCredential
(Utils.ConfigKey(
"smtpusername"), Utils.ConfigKey("smtppassword"));

                MailMessage email = new MailMessage();

                string[] strArrEmails = sTo.Split(',');
                foreach (string strEmail in strArrEmails)
                {
                    if (!string.IsNullOrEmpty(strEmail))
                        email.To.Add(GetValidEmailID(strEmail.Trim()));
                }

                email.From = new MailAddress(sFrom);

                if (!String.IsNullOrEmpty(sCc))
                    email.CC.Add(sCc);
                if (!String.IsNullOrEmpty(sBcc))
                    email.Bcc.Add(sBcc);

                if (!String.IsNullOrEmpty(sSubject))
                    email.Subject = sSubject;

                email.Body = sBody;
                email.IsBodyHtml = true;
                Thread email1 = new Thread(delegate ()
                {
                    SmtpMail.Send(email);
                });
                email1.IsBackground = true;
                email1.Start();
                message = "success";
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return message;
        }

        public static string SendEmailHtmlAttGmail
(string sTo, string sFrom, string sCc,
 string sBcc, string sSubject, string sBody, ArrayList files)
        {
            string message = string.Empty;
            try
            {
                SmtpClient SmtpMail = new SmtpClient(
Utils.ConfigKey("smtphost"));
                SmtpMail.Port = Utils.ToInt(
Utils.ConfigKey("smtpport"));
                SmtpMail.EnableSsl = true;
                SmtpMail.UseDefaultCredentials = true;
                SmtpMail.Credentials = 
new System.Net.NetworkCredential(
Utils.ConfigKey
("smtpusername"), Utils.ConfigKey("smtppassword"));

                MailMessage email = new MailMessage();

                string Body = "";
                string sUrl = 
System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
                //Body = "<HTML><HEAD>";
                Body += "<BASE href='" + sUrl + "'>";
                Body += sBody;

                string[] strArrEmails = sTo.Split(',');
                foreach (string strEmail in strArrEmails)
                {
                    if (!string.IsNullOrEmpty(strEmail))
                        email.To.Add(GetValidEmailID(strEmail.Trim()));
                }

                email.From = new MailAddress(sFrom);

                if (!String.IsNullOrEmpty(sCc))
                    email.CC.Add(sCc);
                if (!String.IsNullOrEmpty(sBcc))
                    email.Bcc.Add(sBcc);

                if (!String.IsNullOrEmpty(sSubject))
                    email.Subject = sSubject;

                email.Body = sBody;
                email.IsBodyHtml = true;

                if (files != null && files.Count > 0)
                {
                    foreach (object o in files)
                    {
                        string file = o.ToString();
                        //Adds the Attachment
                        try
                        {
                            email.Attachments.Add(new Attachment(file));
                        }
                        catch
                        {
                        }
                    }
                }
                Thread email1 = new Thread(delegate ()
                {
                    SmtpMail.Send(email);
                });
                email1.IsBackground = true;
                email1.Start();
               
                message = "success";
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return message;
        }

        public static string SendEmail(string sTo,
 string sFrom, string sCc, string sBcc,
 string sSubject, string sBody)
        {
            string message = string.Empty;
            try
            {
                SmtpClient SmtpMail = new SmtpClient(
Utils.ConfigKey("smtphost_live"));
                SmtpMail.Credentials = new System.Net.NetworkCredential
(Utils.ConfigKey
("smtpusername_live"), Utils.ConfigKey("smtppassword_live"));

                MailMessage email = new MailMessage();

                string[] strArrEmails = sTo.Split(',');
                foreach (string strEmail in strArrEmails)
                {
                    if (!string.IsNullOrEmpty(strEmail))
                        email.To.Add(GetValidEmailID(strEmail.Trim()));
                }

                email.From = new MailAddress(sFrom);

                if (!String.IsNullOrEmpty(sCc))
                    email.CC.Add(sCc);
                if (!String.IsNullOrEmpty(sBcc))
                    email.Bcc.Add(sBcc);

                if (!String.IsNullOrEmpty(sSubject))
                    email.Subject = sSubject;

                email.Body = sBody;
                email.IsBodyHtml = true;

                Thread email1 = new Thread(delegate ()
                {
                    SmtpMail.Send(email);
                });
                email1.IsBackground = true;
                email1.Start();

                message = "success";
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return message;
        }

        public static string SendEmailHtmlAtt(
string sTo, string sFrom, string sCc, 
string sBcc, string sSubject, string sBody, ArrayList files)
        {
            string message = string.Empty;
            try
            {
                SmtpClient SmtpMail = new SmtpClient
(Utils.ConfigKey("smtphost_live"));
                SmtpMail.Credentials =
 new System.Net.NetworkCredential
(Utils.ConfigKey("smtpusername_live"),
 Utils.ConfigKey("smtppassword_live"));
                MailMessage email = new MailMessage();

                string Body = string.Empty;

                string sUrl = 
System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
                //Body = "<HTML><HEAD>";
                Body += "<BASE href='" + sUrl + "'>";
                Body += sBody;

                string[] strArrEmails = sTo.Split(',');
                foreach (string strEmail in strArrEmails)
                {
                    if (!string.IsNullOrEmpty(strEmail))
                        email.To.Add(GetValidEmailID(strEmail.Trim()));
                }

                email.From = new MailAddress(sFrom);

                if (!String.IsNullOrEmpty(sCc))
                    email.CC.Add(sCc);
                if (!String.IsNullOrEmpty(sBcc))
                    email.Bcc.Add(sBcc);

                if (!String.IsNullOrEmpty(sSubject))
                    email.Subject = sSubject;

                email.Body = sBody;
                email.IsBodyHtml = true;

                if (files != null && files.Count > 0)
                {
                    foreach (object o in files)
                    {
                        string file = o.ToString();
                        // Adds the Attachment
                        try
                        {
                            email.Attachments.Add(new Attachment(file));
                        }
                        catch
                        {
                        }
                    }
                }

                Thread email1 = new Thread(delegate ()
                {
                    SmtpMail.Send(email);
                });
                email1.IsBackground = true;
                email1.Start();

                message = "success";
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return message;
        }

        public static string GetValidEmailID(string strEmailID)
        {
            return strEmailID.Replace(";", ",").Replace(" ", "");
        }

        #endregion
    }
}

9). Now You Need To Create Html File That Is HTML Mailer 
the file Name is Verify Changepass.html (note :you can write any 
name you want and same name you canaccess when you are acces it on
 controller action method) and Save It Share folder Of View directory

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<style type="text/css">
    /* FONTS */
    @import url(
'https://fonts.googleapis.com/css?family=Poppins:100,
100i,200,200i,300,300i,400,400i,500,
500i,600,600i,700,700i,800,800i,900,900i');

    /* CLIENT-SPECIFIC STYLES */
    body, table, td, a 
{ 
-webkit-text-size-adjust: 100%;
 -ms-text-size-adjust: 100%;
 }
  table, td
 { 
mso-table-lspace: 0pt; mso-table-rspace: 0pt;
 }
img 
{ 
-ms-interpolation-mode: bicubic;
 }

    /* RESET STYLES */
    img { 
border: 0; height: auto;
 line-height: 100%;
 outline: none;
 text-decoration: 
none; }
    table {
 border-collapse: collapse !important;
 }
    body { height: 100% !important; 
margin: 0 !important;
 padding: 0 !important;
 width: 100% !important;
 }

    /* iOS BLUE LINKS */
    a[x-apple-data-detectors] 
{
        color: inherit !important;
        text-decoration: none !important;
        font-size: inherit !important;
        font-family: inherit !important;
        font-weight: inherit !important;
        line-height: inherit !important;
    }

    /* MOBILE STYLES */
    @media screen and (max-width:600px)
{
        h1 {
            font-size: 32px !important;
            line-height: 32px !important;
        }
    }

    /* ANDROID CENTER FIX */
    div[style*="margin: 16px 0;"] { margin: 0 !important; }
</style>
</head>
<body style="background-color: #f3f5f7; 
margin: 0 !important; padding: 0 !important;">

<!-- HIDDEN PREHEADER TEXT -->
<div style="display: none; font-size: 1px;
 color: #fefefe; line-height: 1px;
 font-family: 'Poppins', sans-serif; 
max-height: 0px; max-width: 0px; opacity: 0;
overflow: hidden;">
    We're thrilled to have you here! Get ready to dive into your
 new account.
</div>

<table border="0" cellpadding="0" cellspacing="0" width="100%" 
style="background:url('../../images/banner-1.jpg');
background-repeat:no-repeat;background-size:100% 100%;">
    <!-- LOGO -->
    <tr>
        <td align="center">
            <!--[if (gte mso 9)|(IE)]>
            <table align="center" border="0"
 cellspacing="0" cellpadding="0" width="600">
            <tr>
            <td align="center" valign="top" 
width="600">
            <![endif]-->
            <table border="0" cellpadding="0" 
cellspacing="0" width="100%"
 style="max-width: 600px;">
                <tr>
                    <td align="center" valign="top" 
style="padding: 40px 10px 40px 10px;">
                        <a href="{HomeUrl}"
 target="_blank" style="text-decoration: none;">
                            <img src="{logoUrl}" />
                        </a>
                    </td>
                </tr>
            </table>
            <!--[if (gte mso 9)|(IE)]>
            </td>
            </tr>
            </table>
            <![endif]-->
        </td>
    </tr>
    <!-- HERO -->
    <tr>
        <td align="center" style="padding: 0px 10px 0px 10px;">
            <!--[if (gte mso 9)|(IE)]>
            <table align="center" border="0" 
cellspacing="0" cellpadding="0" width="600">
            <tr>
            <td align="center" valign="top" width="600">
            <![endif]-->
            <table border="0" cellpadding="0" 
cellspacing="0" width="100%" 
style="max-width: 600px;">
                <tr>
                    <td bgcolor="#ffffff" 
align="center" valign="top" 
style="padding: 40px 20px 20px 20px; 
border-radius: 4px 4px 0px 0px; color: #111111; 
font-family: 'Poppins', sans-serif; 
font-size: 48px; font-weight: 400; 
letter-spacing: 2px; line-height: 48px;">
Hi {CandidateFname} {CandidateLname}
                        <h1 style="font-size: 42px;
 font-weight: 400; margin: 0;"> 
 Trouble signing in?</h1>
                    </td>
                </tr>
            </table>
            <!--[if (gte mso 9)|(IE)]>
            </td>
            </tr>
            </table>
            <![endif]-->
        </td>
    </tr>
    <!-- COPY BLOCK -->
    <tr>
        <td align="center" style="padding: 0px 10px 0px 10px;">
            <!--[if (gte mso 9)|(IE)]>
            <table align="center" border="0" 
cellspacing="0" cellpadding="0" width="600">
            <tr>
            <td align="center" valign="top" width="600">
            <![endif]-->
            <table border="0" cellpadding="0"
 cellspacing="0" width="100%" 
style="max-width: 600px;">
                <!-- COPY -->
                <tr>
                    <td bgcolor="#ffffff" align="left"
 style="padding: 20px 30px 40px 30px; color: #666666;
 font-family: 'Poppins', sans-serif; 
font-size: 16px; font-weight: 400; 
line-height: 25px;">
                        <p style="margin: 0;">{CandidateMessage}</p>
                    </td>
                </tr>
                <!-- BULLETPROOF BUTTON -->
                <tr>
                    <td bgcolor="#ffffff" align="left">
                        <table width="100%" border="0" 
cellspacing="0" cellpadding="0">
                            <tr>
                                <td bgcolor="#ffffff" align="center" 
style="padding: 20px 30px 60px 30px;">
                                    <table border="0"
 cellspacing="0" cellpadding="0">
                                        <tr>
                                            <td align="center"
 style="border-radius: 3px;" bgcolor="#398bf7"><a href="{link}" 
target="_blank" style="font-size: 18px; 
font-family: Helvetica, Arial, sans-serif;
 color: #ffffff; text-decoration: none;
 color: #ffffff; text-decoration: none;
 padding: 12px 50px; border-radius: 2px; 
border: 1px solid #398bf7; display: inline-block;">
Reset Password</a></td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>

                <tr>
                    <td bgcolor="#ffffff" align="left"
 style="padding: 0px 30px 0px 30px; color: #666666;
 font-family: &apos;Lato&apos;,
 Helvetica, Arial, sans-serif; font-size: 16px;
 font-weight: 400; line-height: 25px;">
                        <p style="margin: 0;">
If that doesn't work, copy and 
paste the following link in your browser:</p>
                    </td>
                </tr>
                <!-- COPY -->
                <tr>
                    <td bgcolor="#ffffff" align="left" 
style="padding: 20px 30px 20px 30px;
 color: #666666; font-family: &apos;Lato&apos;
, Helvetica, Arial, sans-serif;
 font-size: 12px; font-weight: 400; line-height: 25px;">
                        <p style="margin: 0;">
                            {url}
                        </p>
                    </td>
                </tr>
                <!-- COPY -->
                <tr>
                    <td bgcolor="#ffffff" align="left" 
style="padding: 0px 30px 20px 30px; 
color: #aaaaaa; font-family: &apos;Lato&apos;
, Helvetica, Arial, sans-serif;
 font-size: 13px;
 font-weight: 400; line-height: 25px;">
                        <p style="margin: 0;
 text-align: center;">
If you did not make this request, 
just ignore this email. Otherwise, pleas click 
button above to change your password.</p>
                    </td>
                </tr>
                <!-- COPY -->
                <tr>
                    <td bgcolor="#ffffff" 
align="left" style="
padding: 0px 30px 40px 30px; 
border-radius: 0px 0px 0px 0px;
 color: #666666; 
font-family: 'Poppins', sans-serif; 
font-size: 14px; font-weight: 400;
 line-height: 25px;">
                        <p style="margin: 0;">{Owner},<br>Team</p>
                    </td>
                </tr>
            </table>
            <!--[if (gte mso 9)|(IE)]>
            </td>
            </tr>
            </table>
            <![endif]-->
        </td>
    </tr>
    <!-- SUPPORT CALLOUT -->
    <tr>
        <td align="center" style="padding: 10px 10px 0px 10px;">
            <!--[if (gte mso 9)|(IE)]>
            <table align="center" border="0"
 cellspacing="0" cellpadding="0" width="600">
            <tr>
            <td align="center" valign="top" width="600">
            <![endif]-->
            <table border="0" cellpadding="0" 
cellspacing="0" width="100%" 
style="max-width: 600px;">
                <!-- HEADLINE -->
                <tr>
                  <td bgcolor="#398bf7" align="center" 
style="padding: 30px 30px 30px 30px;
 border-radius: 4px 4px 4px 4px; color: #666666; 
font-family: 'Poppins', sans-serif;
 font-size: 16px; font-weight: 400; line-height: 25px;">
                    <h2 style="font-size: 16px;
 font-weight: 400; color: #ffffff;
 margin: 0;">Need more help?</h2>
                    <p style="margin: 0;
 font-size: 14px;">
<a href="{Contactus}" target="_blank" 
style="color: #ffffff;">We&rsquo;re here, 
ready to talk</a></p>
                  </td>
                </tr>
            </table>
            <!--[if (gte mso 9)|(IE)]>
            </td>
            </tr>
            </table>
            <![endif]-->
        </td>
    </tr>
    <!-- FOOTER -->
    
</table>

</body>
</html>

10). Now You Need To Acces This HTML File Into Action Method

Here I Am Using Account Controller To Sent Verify Link 

using myProject.BAL.Utility;
using myProject.DataEntity;
using myProject.Models;
using Newtonsoft.Json;
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace myProject.Controllers
{
    [Authorize]
    [OutputCache(CacheProfile = "Default")]
    public class AccountController : Controller
    {
 [AllowAnonymous]
        public ActionResult ForgotPwd()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [AllowAnonymous]
        public ActionResult ForgotPwd(string userName)
        {
            try
            {
                // mail or sms send to user.

                var uD = _ac.CheckUserNameIsExist(userName);
                if (uD.UserID > 0)
                {
                    var userId = uD.UserID;
                    var guid = Guid.NewGuid();
                    var lnkHref = "<a href='" + Url.Action("ResetPassword", 
"Account",
 new { email = userName, code = guid }, "http")
 + "' target='_blank' style='color: #398bf7;'>Conferm Account</a>";
                    var sTo = _ac.GetActiveUser(userName).EmailID;
                    var sFrom = "careers@techgnite.com";
                    var sCc = "";
                    var sBcc = "";
                    var sSubject = "Password Reset Url";
                    //     
                    string body = string.Empty;
               //now we Are reading Html Template 
                    using (StreamReader reader = new StreamReader(
Server.MapPath
                       ("~/Views/Shared/Changepass.html")))
                    {
                        body = reader.ReadToEnd();
                    }
                    body = body.Replace("{HomeUrl}",
 Url.Action("index", "Home",
 "", "http"));
                    body = body.Replace("{logoUrl}",
 Url.Content("~/images/logo.png"));
                    body = body.Replace("{CandidateFname}", uD.FName);
                    body = body.Replace("{CandidateLname}", uD.LName);
                    body = body.Replace("{FullCandidatePhone}", 
uD.HomePhone);
                    body = body.Replace("{CandidateEmail}", uD.EmailID);
                    body = body.Replace("{link}", 
Url.Action("ResetPassword", "Account",
 new { email = userName, code = guid }, "http"));
                    body = body.Replace("{CandidateMessage}", 
"There is a request to change 
your password. Resetting your password is easy.
 Just press the button below and follow the 
instructions. We'll have you up and running in no time.");
                    body = body.Replace("{Password}",
 Utils.GetSHA1HashData(uD.Password));
                    body = body.Replace("{url}", lnkHref);
                    body = body.Replace("{Owner}", "MyHealthRecords");
                    body = body.Replace("{Contactus}",
 Url.Action("Contact", "Home", new 
{ email = userName, code = guid }, "http"));

                    var result = MailHelper.SendEmailGmail
(sTo, sFrom, sCc, sBcc, 
sSubject, body);
                    //

                    if (result == "success")
                    {
                        _ac.UpdateGUID_UserDetail(userId, guid);
                    }
                    return RedirectToAction("Login");
                }

                ViewBag.UserNameError = "Username does not exist !";
                return View();
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                throw;
            }
        }
    }
}

10).  Now You Need To Add View Of Action Method

@{
    ViewBag.Title = "ForgotPwd";
    Layout = "~/Views/Shared/_AccountLayoutPage.cshtml";
}

<div class="hold-transition login-page">
 <div class="login-box">
  <div class="login-logo">
   <a href="#"><img src="~/Images/Logo.png"
 alt="logo.png" title="Power+HMS" 
class="img-fluid" /></a>
  </div>
  <!-- /.login-logo -->
  <div class="login-box-body pb-20">
   <p class="login-box-msg text-uppercase">Recover password</p>
   <form novalidate action="~/Account/ForgotPwd" 
method="post" class="form-element">
    <div class="form-group">
     <div class="floating-label">
      <input type="text" class="floating-input" 
name="userName" id="userName" 
placeholder=" ">
      <label>Email</label>
     </div>
    </div>
    <div class="row">
     <div class="col-12 text-center">
      <button type="submit" 
class="btn btn-info btn-block text-uppercase">
Reset</button>
     </div>
    </div>
   </form>
  </div>
  <!-- /.login-box-body -->
 </div>
</div>

No comments:

Post a Comment

Thank You For Your Great Contribution

Featured Post

how to find n number of nodes have child or cildren

 how to find n number of nodes have child or cildren for that we use recursive function  const   data = {     'id' : '0' ,...

Popular Posts