I am new to ASP.NET and C# and this is my first big project.
Unable to send forgot password mail through ASP.NET and C#. Even, neither errors nor exceptions are displayed by Visual Studio.
These are my files:
Code Behind
//Reset password event
protected void btnResetPassword_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spResetPassword", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramUsername = new SqlParameter("@UserName", txtUserName.Text);
cmd.Parameters.Add(paramUsername);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (Convert.ToBoolean(rdr["ReturnCode"]))
{
SendPasswordResetEmail(rdr["EmailID"].ToString(), txtUserName.Text, rdr["UniqueId"].ToString());
lblMessage.Text = "An email with instructions to reset your password is sent to your registered email";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Username not found!";
}
}
}
}
Send Email to Recipient, an email template is been added inline code instead of a using AlternateView.
private void SendPasswordResetEmail(string ToEmail, string UserName, string UniqueId)
{
try
{
MailMessage mailMessage = new MailMessage("Email@gmail.com", ToEmail);
StringBuilder sbEmailBody = new StringBuilder();
sbEmailBody.Append("Dear " + UserName + ",<br/><br/>");
sbEmailBody.Append("Please click on the following link to reset your password");
sbEmailBody.Append("<br/>"); sbEmailBody.Append("http://localhost:64736/SmartE/Registration/ChangePassword.aspx?uid=" + UniqueId);
sbEmailBody.Append("<br/><br/>");
sbEmailBody.Append("<b>Smart Elector</b>");
mailMessage.IsBodyHtml = true;
mailMessage.Body = sbEmailBody.ToString();
mailMessage.Subject = "Reset Your Password";
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = "Email@gmail.com",
Password = "Password"
};
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
}
catch(Exception ex)
{
lblMessage.Text= "Record Insert Exception: " + ex.Message;
}
}
Stored procedure:
There is no output parameter defined in this stored procedure, which returns the unique code to the invoker. instead, select query is used to return the same.
CREATE PROCEDURE Spresetpassword
@UserName NVARCHAR(100)
AS
BEGIN
DECLARE @UserID INT,
@EmailID NVARCHAR(100);
SELECT
@UserID = userid,
@EmailID = emailid
FROM
globalusers
WHERE
username = @UserName;
IF (@UserID IS NOT NULL)
BEGIN
-- If username exists
DECLARE @GUID UNIQUEIDENTIFIER;
SET @GUID = NEWID();
INSERT INTO tblresetpasswordrequests (id, userid, resetrequestdatetime)
VALUES (@GUID, @UserID, GETDATE())
SELECT
1 AS ReturnCode,
@GUID AS UniqueId,
@EmailID AS EmailID
END
ELSE
BEGIN
-- If username does not exist
SELECT
0 AS ReturnCode,
NULL AS UniqueId,
NULL AS EmailID
END
END