Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 激活电子邮件/链接不工作_Asp.net_Sql_Vb.net_Email_Activation - Fatal编程技术网

Asp.net 激活电子邮件/链接不工作

Asp.net 激活电子邮件/链接不工作,asp.net,sql,vb.net,email,activation,Asp.net,Sql,Vb.net,Email,Activation,我正在尝试发送一封激活电子邮件,并让用户通过单击提供的链接激活他们的帐户。我一直在根据在线查看的开源代码对其进行调整,但最近它停止发送电子邮件,没有给出任何错误。这是带有发送电子邮件功能的注册表格: Imports System.Data.SqlClient Imports System.Data.Sql Imports System.Data.SqlTypes Imports System.Data Imports System.Configuration Imports System.Net

我正在尝试发送一封激活电子邮件,并让用户通过单击提供的链接激活他们的帐户。我一直在根据在线查看的开源代码对其进行调整,但最近它停止发送电子邮件,没有给出任何错误。这是带有发送电子邮件功能的注册表格:

Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports System.Data
Imports System.Configuration
Imports System.Net.Mail
Imports System.Net
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls


Public Class WebForm1
Inherits System.Web.UI.Page

Dim boolCar As Object

Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
    If txtEmailAddress.Text.Trim.EndsWith("@umary.edu") Or txtPassword.Text.Trim = txtRetypePassword.Text.Trim Then
        Dim con As New SqlConnection
        Dim cmdEmail As New SqlCommand
        Dim cmdRegistration As New SqlCommand
        Dim EmailCount As Integer = 0

        Try
            con.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
            con.Open()

            cmdEmail = New SqlCommand("SELECT COUNT(UMaryEmail) As EmailCount FROM RegisteredUsers WHERE UMaryEmail='" & txtEmailAddress.Text.Trim & "'", con)
            EmailCount = cmdEmail.ExecuteScalar()

            If EmailCount = 0 Then
                ' Declare database input variables 
                Dim userId As Integer = 0
                Dim firstName As String = txtFirstName.Text
                Dim lastName As String = txtLastName.Text
                Dim hometown1 As String = txtHometown1.Text
                Dim state1 As String = txtState1.Text
                Dim zip1 As String = txtZipCode1.Text
                Dim hometown2 As String = txtHometown2.Text
                Dim state2 As String = txtState2.Text
                Dim zip2 As String = txtZipCode2.Text
                Dim phoneNum As String = txtPhoneNumber.Text
                Dim emailAddress As String = txtEmailAddress.Text
                Dim password As String = txtPassword.Text
                Dim boolCar As Boolean = False
                Dim boolUmary As Boolean = False

                If radYesNo.SelectedIndex = 0 Then
                    boolCar = True
                Else
                    boolCar = False
                End If

                ' Define the command using parameterized query 
                cmdRegistration = New SqlCommand("INSERT INTO RegisteredUsers(FirstName, LastName, Hometown1, State1, ZIP1, Hometown2, State2, ZIP2, PhoneNum, UMaryEmail, Password, Car) VALUES (@txtFirstName, @txtLastName, @txtHometown1, @txtState1, @txtZipCode1, @txtHometown2, @txtState2, @txtZipCode2, @txtPhoneNumber, @txtEmailAddress, @txtPassword, @RadYesNo)", con)

                ' Define the SQL parameter '
                cmdRegistration.Parameters.AddWithValue("@txtFirstName", txtFirstName.Text)
                cmdRegistration.Parameters.AddWithValue("@txtLastName", txtLastName.Text)
                cmdRegistration.Parameters.AddWithValue("@txtHometown1", txtHometown1.Text)
                cmdRegistration.Parameters.AddWithValue("@txtState1", txtState1.Text)
                cmdRegistration.Parameters.AddWithValue("@txtZipCode1", txtZipCode1.Text)
                cmdRegistration.Parameters.AddWithValue("@txtHometown2", txtHometown2.Text)
                cmdRegistration.Parameters.AddWithValue("@txtState2", txtState2.Text)
                cmdRegistration.Parameters.AddWithValue("@txtZipCode2", txtZipCode2.Text)
                cmdRegistration.Parameters.AddWithValue("@txtPhoneNumber", txtPhoneNumber.Text)
                cmdRegistration.Parameters.AddWithValue("@txtEmailAddress", txtEmailAddress.Text)
                cmdRegistration.Parameters.AddWithValue("@txtPassword", txtPassword.Text)
                cmdRegistration.Parameters.AddWithValue("@RadYesNo", boolCar)

                cmdRegistration.ExecuteNonQuery()
                SendActivationEmail(userId)
                Response.Redirect("RegistrationSuccess.aspx")
            Else
                ' Duplicate Email Exist Error Message
                MsgBox("Email address already supplied.")
            End If
            ' Catch ex As Exception (Not needed)
            ' Error Executing One Of The SQL Statements 
        Finally
            con.close()
        End Try
    Else
        ' Throw Error Message 
        MsgBox("Email input error")
    End If
End Sub

   Private Sub SendActivationEmail(userId As Integer)
    Dim sqlString As String = "Server=SERVERNAME;Database=StudentGov;UId=sa;Password=Password1;"
    Dim ActivationCode As String = Guid.NewGuid().ToString()
    Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
    Using con As New SqlConnection(sqlString)
        Using sqlCmd As New SqlCommand("UPDATE RegisteredUsers SET UserId = '" + userId.ToString + "', ActivationCode = '" + ActivationCode.ToString + "' WHERE UMaryEmail='" + txtEmailAddress.Text + "';")
            Using sda As New SqlDataAdapter()
                sqlCmd.CommandType = CommandType.Text
                sqlCmd.Parameters.AddWithValue("@UserId", userId)
                sqlCmd.Parameters.AddWithValue("@ActivationCode", ActivationCode)
                sqlCmd.Connection = con
                con.Open()
                sqlCmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Using
    Using mm As New MailMessage("****@outlook.com", txtEmailAddress.Text)
        mm.Subject = "Account Activation"
        Dim body As String = "Hello " + txtFirstName.Text.Trim() + ","
        body += "<br /><br />Please click the following link to activate your account"
        body += "<br /><a href='" & ActivationUrl & "'>Click here to activate your account.</a>"
        body += "<br /><br />Thanks"
        mm.Body = body
        mm.IsBodyHtml = True
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.live.com"
        smtp.EnableSsl = True
        Dim NetworkCred As New NetworkCredential("****@outlook.com", "****")
        smtp.UseDefaultCredentials = True
        smtp.Credentials = NetworkCred
        smtp.Port = 587
        Try
            smtp.Send(mm)
        Catch ex As Exception
            MsgBox("Email was not sent")
        End Try
    End Using
End Sub

Private Function FetchUserId(emailAddress As String) As String
    Dim cmd As New SqlCommand()
    Dim con As New SqlConnection("Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1")

    cmd = New SqlCommand("SELECT UserId FROM RegisteredUsers WHERE UMaryEmail=@txtEmailAddress", con)
    cmd.Parameters.AddWithValue("@txtEmailAddress", emailAddress)
    If con.State = ConnectionState.Closed Then
        con.Open()
    End If
    Dim userId As String = Convert.ToString(cmd.ExecuteScalar())
    con.Close()
    cmd.Dispose()
    Return userId
End Function
End Class
以下是AccountActivation页面:

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration


Public Class ActivateAccount
Inherits System.Web.UI.Page

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        ActivateMyAccount()
    End If
End Sub


Private Sub ActivateMyAccount()
    Dim con As New SqlConnection()
    Dim cmd As New SqlCommand()

    Try
        con.ConnectionString = "Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
        If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("UMaryEmail"))) Then

            'approve account by setting Is_Approved to 1 i.e. True in the sql server table
            cmd = New SqlCommand("UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=@UserId AND UMaryEmail=@txtEmailAddress", con)
            cmd.Parameters.AddWithValue("@UserId", Request.QueryString("UserId"))

            cmd.Parameters.AddWithValue("@txtEmailAddress", Request.QueryString("UMaryEmail"))
            If con.State = ConnectionState.Closed Then
                con.Open()

            End If
            cmd.ExecuteNonQuery()
            Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")

        End If
    Catch ex As Exception
        ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
        Return
    Finally
        con.Close()
        cmd.Dispose()
    End Try
End Sub
End Class

你可能已经知道了,我很困惑。由于没有收到错误消息,我不知道为什么SendActivationEmail功能不再工作。谁来帮忙!:

嗨,FlummoxedUser你确定你也检查了你的代码吗

请看这里:

 Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
我认为最好使用httputility.urlEncode/Decode来处理这个问题,它使用它只过滤每个函数或单个变量的结果

第二,注意上面的代码

这在您的页面中:

  If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("UMaryEmail"))) 
您在哪里找到您的查询字符串参数中的UmaryEmail密钥

选中它,您将解决您的问题,但也可以在激活页面中选中cmd等,否则您将出现一些问题:

我希望它能帮助你,如果它解决了你的问题,请将此标记为答案

更新:

>   Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
通过此任务,您可以创建yout激活链接,该链接类似于

http://localhost:63774/ActivateAccount.aspx?userId=1&txtEmailAddress=email@pippo&ActivationCode=123456
现在,当单击链接服务器处理请求并创建包含查询字符串中所有键的集合数据时,会追加什么

实际上,您可以使用request.QueryString检查/检索每个键的值。因此,您可以按所做的那样使用request.Querystringkeyname来获取该特定参数的值,但在您的情况下,您可以检查未传递到链接中的键。请注意,您只设置了3个键,它们是

用户ID

txtEmailAddress

激活码

请求查询字符串中没有UMaryEmail密钥

另外一个重要的东西永远不会在查询字符串数据库字段中传递:使用不反映数据库字段的fantasy name或shortname

例如:

UserID=>uid

ActivatioCode=令牌、acd、cd或您想要的任何东西

txtEmailAddress=电子邮件、em或任何其他名称

现在激活页面问题当您尝试检查您的值时,请使用if语句检查userid key和umarymail,其中userid可以匹配,因为它存在于查询字符串中,但umarymail不在请求中。querystring您没有提供它,因此如果失败,页面中没有显示任何内容

在这里,您可以重新访问激活子系统,并提供一些评论,以便更好地理解:

  Private Sub ActivateMyAccount()
    'Checking you keys in querystring

    If Request.QueryString.AllKeys.Contains("Userid") AndAlso Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
        'here we assume that keys exist and so we can proceed with rest 
        If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
            'no we can proceed to make other stuff 
            'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :

            'classic example for create a connection with web config file
            ' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
            Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")

                If con.State = ConnectionState.Closed Then con.Open()
                Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=@UserId AND UMaryEmail=@txtEmailAddress"
                Using cmd As New SqlCommand(sqlQuery, con)
                    Try
                        With cmd
                            .Parameters.AddWithValue("@UserId", Request.QueryString("UserId"))
                            .Parameters.AddWithValue("@txtEmailAddress", Request.QueryString("txtEmailAddress"))
                            .ExecuteNonQuery()
                            Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
                        End With
                    Catch ex As Exception
                        ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
                    End Try

                End Using
            End Using
        Else
            Response.Write("<h1>invalid activation links!!</h1>")
        End If
    Else
        Response.Write("<h1>invalid activation links!!</h1>")
    End If
End Sub
但一切都错了让我解释一下:

Declar您的变量:Dim ActivationUrl作为字符串它是正确的 然后构建url以便:

="http://localhost:63774/ActivateAccount.aspx?userId=" & HttpUtility.UrlEncode(FetchUserId(txtEmailAddress.text.tostring)) & "&txtEmailAddress=" & HttpUtility.UrlEncode(txtEmailAddress.text.tostring) & "&ActivationCode=" & HttpUtility.UrlEncode(ActivationCode.ToString))
其中查看一段代码,它是您的:“HttpUtility.UrlEncodetxtEmailAddress.ToString”,以这种方式,您正在传递一个值系统类型对象,该对象是一个textbox,用于传递您需要访问其.Text属性(如txtEmailAddress.Text)的textbox值

按照我上面的代码进行更改,如果您的过程正确,它将工作

**更新代码3**

使用此更改您的代码。§小心不要更改任何内容复制并粘贴所有ActivateMyAccount子帐户并删除旧帐户

Private Sub ActivateMyAccount()
    'Checking you keys in querystring

    If Request.QueryString.AllKeys.Contains("userId") And Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
        'here we assume that keys exist and so we can proceed with rest 
        If (Not String.IsNullOrEmpty(Request.QueryString("userId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
            'no we can proceed to make other stuff 
            'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :

            'classic example for create a connection with web config file
            ' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
            Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")

                If con.State = ConnectionState.Closed Then con.Open()
                Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=@UserId AND UMaryEmail=@txtEmailAddress"
                Using cmd As New SqlCommand(sqlQuery, con)
                    Try
                        With cmd
                            cmd.Parameters.AddWithValue("@UserId", Request.QueryString("userId"))
                            cmd.Parameters.AddWithValue("@txtEmailAddress", Request.QueryString("txtEmailAddress"))
                            cmd.ExecuteNonQuery()
                            Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
                        End With
                    Catch ex As Exception
                        ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
                    End Try

                End Using
            End Using
        Else
            Response.Write("<h1>invalid activation links!! bad query string</h1>")
        End If
    Else
        Response.Write("<h1>invalid activation links!! bad not string</h1>")
    End If
End Sub

只需对您的工作版本进行一次差异备份。除非我错过了它,否则您希望如何获得错误消息:ASP.Net中的MsgBox是什么,catch似乎被注释掉了?catch as ex异常被注释掉了,因为它不需要。写入数据库的SQL命令工作正常。它写得正确,唯一的问题是电子邮件没有发送,上次我尝试时,电子邮件中提供的激活链接也不起作用,它只是重定向到一个空白页面。好的,我再次收到电子邮件,但来自电子邮件链接的页面仍然没有显示任何内容,完全空白。恐怕我不明白你想说什么关于UMaryEmail密钥。它被定义为上述注册/注册页面下的参数之一。在SQL数据库中,email address列名为UMaryEmail,因此我在if语句查询中使用了该名称,而不是emailaddress或txtEmailAddress。我用那个名字错了吗?我将server.htmlencode更改为httputility.urlEncode,但我太缺乏经验,无法理解这两个命令之间的区别。感谢您的回复。几分钟后在帖子中看一看,我将向您展示一些示例:为了帮助您,我已通过对您的代码进行一些更改来更新我的代码,以便向您发送电子邮件。注意:好的,我尝试了您的ActivateMyAccount,但由于某些原因,我没有收到电子邮件。我检查了我的垃圾邮件,但找不到。@FlummoxedUser你说:好的,我尝试了你的ActivateMyAccount,但由于某种原因我没有收到邮件。我对您的激活代码进行了一些更改,因此如果您的邮件未发送,您必须检查上面的代码。调试应用程序以检查是否引发了异常
Private Sub ActivateMyAccount()
    'Checking you keys in querystring

    If Request.QueryString.AllKeys.Contains("userId") And Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
        'here we assume that keys exist and so we can proceed with rest 
        If (Not String.IsNullOrEmpty(Request.QueryString("userId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
            'no we can proceed to make other stuff 
            'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :

            'classic example for create a connection with web config file
            ' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
            Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")

                If con.State = ConnectionState.Closed Then con.Open()
                Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=@UserId AND UMaryEmail=@txtEmailAddress"
                Using cmd As New SqlCommand(sqlQuery, con)
                    Try
                        With cmd
                            cmd.Parameters.AddWithValue("@UserId", Request.QueryString("userId"))
                            cmd.Parameters.AddWithValue("@txtEmailAddress", Request.QueryString("txtEmailAddress"))
                            cmd.ExecuteNonQuery()
                            Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
                        End With
                    Catch ex As Exception
                        ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
                    End Try

                End Using
            End Using
        Else
            Response.Write("<h1>invalid activation links!! bad query string</h1>")
        End If
    Else
        Response.Write("<h1>invalid activation links!! bad not string</h1>")
    End If
End Sub