sqlasp.net发送电子邮件c#

本文关键字:电子邮件 net sqlasp | 更新日期: 2023-09-27 17:59:46

如果你能帮我。。。我正在尝试创建一个忘记密码的方法。访问我的数据库并发送电子邮件。如果你能帮我,因为我没有太多经验。提前感谢您。登录是唯一的。C#

protected void LinkButton1_Click(object sender, EventArgs e)
{
        var sqlCon = new SqlConnection(System.Configuration.ConfigurationManager.
            ConnectionStrings["ConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = sqlCon;
        cmd.CommandText = "select Password from Person where Login= @Login ";
        cmd.Connection.Open();
        string Password = cmd.ExecuteScalar().ToString();
        cmd.Connection.Close();
        cmd.Dispose();
        SqlCommand cmd1 = new SqlCommand();
        cmd1.Connection = sqlCon;
        cmd1.CommandText = "select e_mail from Person where Login= @Login "; 
        cmd1.Connection.Open();
        string e_mail = cmd.ExecuteScalar().ToString();
        cmd.Connection.Close();
        cmd.Dispose();
        if (Login.Text.Equals("@Login"))
        {
           Class1 S = new Class1();
           S.sendMail(e_mail, "Your Password request", Password);
           Response.Write("<script>");
        }
}

sqlasp.net发送电子邮件c#

首先,您可以对sql进行一次调用,而不是两次,试试这样的东西(未测试!)

var sqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("select e_mail, Password from Person where Login= @Login ", sqlCon);            
cmd.Connection.Open();            
cmd.Parameters.Add(new SqlParameter("@Login", Email.Text));
string email = "", password = "";
using (SqlDataReader sdr = cmd.ExecuteReader())
{
    while (sdr.Read())
    {
        email = sdr.GetString(0);
        password = sdr.GetString(1);
    }
}
cmd.Connection.Close();
cmd.Dispose();

SmtpClient mailClient = new SmtpClient("your smtp");
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("YOU");
mailMessage.To.Add(email);
mailMessage.Subject = "password recovery";
mailMessage.Body = "hello " + email + " your password : " + password;
mailMessage.IsBodyHtml = true;
mailClient.Send(mailMessage);

要发送邮件,请使用SmtpClient。在WebConfig中配置客户端。若要创建电子邮件,请使用MailMessage。应该是不言自明的。

我不知道你的用户数据库是如何设计的,但有两个查询来获取数据似乎太多了。构造一个同时返回电子邮件和密码的查询。

另外,不加密用户密码也是一种糟糕的做法。考虑提供一种替代解决方案(例如重置密码而不是返回密码)。