我是ASP.NET和C#的新手,这是我的第一个大项目。
无法通过ASP.NET和C#发送忘记密码的邮件。甚至,Visual Studio不会显示错误或异常。
这些是我的文件:
隐藏代码
//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!";
}
}
}
}
发送电子邮件给收件人,电子邮件模板被添加为内联代码,而不是使用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;
}
}
存储过程:
此存储过程中未定义输出参数,该参数将唯一代码返回给调用者。相反,选择查询用于返回相同的内容。
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
答案 0 :(得分:0)
使用会员资格尝试此解决方案,
protected void btnResetPassword_Click(object sender, EventArgs e)
{
MembershipUser mu = Membership.GetUser(txtResetUserName.Text.Trim());
if (mu != null)
{
if (!mu.IsLockedOut)
{
string resetPassword = Membership.GeneratePassword(8, 1);
mu.ChangePassword(mu.ResetPassword(), resetPassword);
ListDictionary replaceList = new ListDictionary();
replaceList.Add("<%UserName%>", "Name of the user");
replaceList.Add("<%NewCode%>", resetPassword);
Utility fetch = new Utility();
fetch.SendMail(mu.Email, string.Empty, "User account " + txtResetUserName.Text.Trim() + " password reset to: " + resetPassword, fetch.MailBodyTemplate(replaceList, "ResetEmailTemplate"), null);
}
}
}
将以下代码放入您项目的Utility类中。
public void SendMail(string to, string cc, string subject, AlternateView body, string path)
{
MailMessage message = new MailMessage(AppSettings.Default.From, to);
if (!String.IsNullOrEmpty(path)) message.Attachments.Add(new Attachment(path));
if (!String.IsNullOrEmpty(cc)) message.CC.Add(cc);
if (body != null)
{
message.AlternateViews.Add(body);
message.IsBodyHtml = true;
}
message.Body = subject;
message.Subject = subject;
Thread bgThread = new Thread(new ParameterizedThreadStart(SendEmailInBackgroud));
bgThread.IsBackground = true;
bgThread.Start(message);
}
基于模板的电子邮件正文
public AlternateView MailBodyTemplate(ListDictionary replaceList, string fileName)
{
AlternateView plainView = null;
string templatePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/MailTemplate/" + fileName + ".txt");
if (File.Exists(templatePath))
{
string templateContent = File.ReadAllText(templatePath);
foreach (DictionaryEntry item in replaceList)
{
if (item.Value != null)
templateContent = templateContent.Replace(item.Key.ToString(), item.Value.ToString());
else
templateContent = templateContent.Replace(item.Key.ToString(), string.Empty);
}
plainView = AlternateView.CreateAlternateViewFromString(templateContent, null, MediaTypeNames.Text.Html);
}
return plainView;
}
您的电子邮件模板文件如下所示, 文件名:ResetEmailTemplate.txt
<!DOCTYPE html>
<html><head>
<style>
.ContentBody {
color: #1331a0;
}
</style></head>
<body class="ContentBody">
<p>Dear <%UserName%>,</p>
<p>New Password for your accout is: <%NewCode%> </p>
</body>
</html>