Click here to Skip to main content
15,900,724 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

I wants to send a forgotten password of user to him through mail... in Asp.Net Mvc3

First i fetch the email address of user from database.. then i have to send the mail my code is below..

Model class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace TelerikLogin.Models.ViewModels
{
    public class ForgotPassword
    {
        public int user_id { get; set; }
        public string user_login_name { get; set; }
        public string user_password { get; set; }

        [Required]
        [Display(Name="Email Address : ")]
        public string user_email_address { get; set; }
    }
}


View

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TelerikLogin.Models.ViewModels.ForgotPassword>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    ForgotPassword
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>ForgotPassword</h2>
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>

<% using (Html.BeginForm("ForgotPassword", "Account", FormMethod.Post))
   { %>
   
   <%: Html.LabelFor(m => m.user_email_address) %>
   <%: Html.TextBox("user_email_address")%>
      <%: Html.ValidationSummary(true) %>

<input type="submit" value="Submit"/>

   <%} %>

</asp:Content>


Controller

public ActionResult ForgotPassword()
      {
          return View();
      }

      [HttpPost]
      public ActionResult ForgotPassword(string user_email_address)
      {
          SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\MVC3\TelerikLogin\TelerikLogin\App_Data\Login.mdf;Integrated Security=True;User Instance=True");

          DataTable dt1 = new DataTable();

          string strQuery = string.Format("SELECT user_password FROM [user_master] WHERE user_email_address='{0}'",user_email_address);
          conn.Open();
          SqlDataAdapter da1 = new SqlDataAdapter(strQuery, conn);
          da1.Fill(dt1);
          conn.Close();

          if (dt1.Rows.Count > 0)
          {
            //....Here is the code for sending a mail.....

              MailMessage msg = new MailMessage();

              msg.From = new MailAddress("direction@gmail.com");
              msg.To.Add(user_email_address);
              msg.Subject = "Password";
              msg.Body = "Test";
              msg.Priority = MailPriority.High;

              SmtpClient client = new SmtpClient();


              client.Credentials = new NetworkCredential("direction@gmail.com", "direction", "smtp.gmail.com");
              client.Host = "smtp.gmail.com";
              client.Port = 587;
              client.DeliveryMethod = SmtpDeliveryMethod.Network;
              client.EnableSsl = false;
              client.UseDefaultCredentials = true;

              client.Send(msg);

             return RedirectToAction("MailTransfer", "MailT");
          }
          return View();
      }



It gives me an error on below line
client.Send(msg);


And Error is:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. x1sm1264662igc.16


I wanna solve this error.. so need help....

Thanks in advance...
Posted
Updated 8-Mar-12 21:46pm
v4

Use the below code to sent Email:

C#
MailMessage msg = new MailMessage();
msg.From = new MailAddress("yourID@gmail.com");
msg.To.Add("sendID@yahoo.com");
msg.Body = "body my mail";
msg.Subject = "my mail subject";
msg.Priority = MailPriority.High;

SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("yourID@gmail.com", "yourName", "smtp.gmail.com");
client.Host = "smtp.gmail.com";
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = false;
client.UseDefaultCredentials =true;

client.Send(msg);
 
Share this answer
 
Comments
disha desani 9-Mar-12 1:14am    
Hey, @GanesanSenthivel
I tried your code but it gives me an error like below
on client.Send(msg); line
ERROR:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. cv10sm938830igc.13
How to solve it?
Check this out:
ASP.NET MVC3 Password Reset[^]
 
Share this answer
 
Use this code

C#
public int SendUserMail(string fromad, string toad, string body, string header, string subjectcontent)
   {
       int result = 0;
       MailMessage usermail = Mailbodplain(fromad, toad, body, header, subjectcontent);
       SmtpClient client = new SmtpClient();
       //Add the Creddentials- use your own email id and password
       client.Credentials = new System.Net.NetworkCredential("your user id ", "pwd"); ;

       client.Host = "smtp.gmail.com";
       client.Port = 587;
       client.EnableSsl = true;
       try
       {
           client.Send(usermail);
           result = 1;
       }
       catch (Exception ex)
       {
           result = 0;
       } // end try

       return result;

   }
   public MailMessage Mailbodplain(string fromad, string toad, string body, string header, string subjectcontent)
   {
       System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
       try
       {
           string from = fromad;
           string to = toad;
           mail.To.Add(to);
           mail.From = new MailAddress(from, header, System.Text.Encoding.UTF8);
           mail.Subject = subjectcontent;
           mail.SubjectEncoding = System.Text.Encoding.UTF8;
           mail.Body = body;
           mail.BodyEncoding = System.Text.Encoding.UTF8;
           mail.IsBodyHtml = true;
           mail.Priority = MailPriority.High;
       }
       catch (Exception ex)
       {
           throw;
       }
       return mail;
   }
 
Share this answer
 
hi try this write in .aspx page

C#
@{try
     {
         WebMail.SmtpServer = "smtp.gmail.com";
         WebMail.SmtpPort = 587;
         WebMail.EnableSsl = true;
         WebMail.UserName = "frommail@mail.com";
         WebMail.Password = "pwd";
         WebMail.From = "frommail@mail.com";
         WebMail.Send ( "tomail@mail.com", "RSVP Notification", "Your Name" + "is" + "Yes";) + "attending" );
     }
     catch (Exception ex)
     {
       @:<b>Sorry - we couldn't send the email to confirm your RSVP.</b>
 }}


//or write in c#
 MailAddress mailfrom = new MailAddress ( "frommail@gmail.com" );
            MailAddress mailto = new MailAddress ( "tomail@gmail.com" );
            MailMessage newmsg = new MailMessage ( mailfrom, mailto );

            newmsg.Subject = "Subject of Email";
            newmsg.Body = "Body(message) of email";

            ////For File Attachment, more file can also be attached

            Attachment att = new Attachment ( "G:\\code.txt" );
            newmsg.Attachments.Add ( att );

            SmtpClient smtps = new SmtpClient ( "smtp.gmail.com", 587 );
            smtps.UseDefaultCredentials = false;
            smtps.Credentials = new NetworkCredential ( "mail@gmail.com", "pwd" );
            smtps.EnableSsl = true;
            smtps.Send ( newmsg );
 
Share this answer
 
v2
Comments
disha desani 9-Mar-12 23:32pm    
Hi,
I tried your code its working..
Thanks... :)
Bojjaiah 26-Apr-13 1:05am    
Welcome :)
For error...

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. x1sm1264662igc.16


...you need to set EnableSsl to true

C#
client.EnableSsl = true;


for more information, check this answer on StackOverflow[^]. Note the main differences when setting up the SmtpClient

C#
var smtp = new SmtpClient
           {
               Host = "smtp.gmail.com",
               Port = 587,
               EnableSsl = true,
               DeliveryMethod = SmtpDeliveryMethod.Network,
               UseDefaultCredentials = false,
               Credentials = new NetworkCredential("name", "password")
           };
 
Share this answer
 
v2
Comments
disha desani 9-Mar-12 5:17am    
Hey @Dylan Morley
I tried as you said but still it gives me same error.
Dylan Morley 9-Mar-12 5:29am    
See updated answer
Member 10278272 15-Feb-14 1:46am    
it gives me error like The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. please solve.. thank you
disha desani 9-Mar-12 23:33pm    
okk thanks for suggestion..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900