激活电子邮件/链接不起作用

时间:2014-04-25 23:24:12

标签: 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.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功能不再有效。有人帮忙! :(

1 个答案:

答案 0 :(得分:0)

你好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)

通过此任务,您可以创建类似

的激活链接
http://localhost:63774/ActivateAccount.aspx?userId=1&txtEmailAddress=email@pippo&ActivationCode=123456

现在点击该链接服务器句柄请求并创建包含查询字符串中所有键的集合数据时附加什么

实际上,您可以使用request.QueryString来检查/检索每个键的值。所以你可以按照你的request.Querystring(“keyname”)来获取该特定参数的值BUT在你的情况下检查一个没有传递给链接的密钥。请注意,您只设置了3个

用户ID

txtEmailAddress

ActivationCode

请求查询字符串

中没有“UMaryEmail”键

另一个重要的东西永远不会在QUERY STRING DATABASE FIELD中传递:)使用不反映数据库字段的幻想名称或短名称

示例:

UserID =&gt;流体

ActivatioCode = token,acd,cd或任何你想要的东西

txtEmailAddress = email,em或任何其他名称

现在激活页面问题,当您尝试检查您的值时,使用if语句检查userid密钥和UMaryEmail,其中userid可以匹配,因为它存在于查询字符串中,但UmaryEmail不在您没有提供的request.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

如果您的查询是正确的,它应该在第一次拍摄:) 试试让我知道,如果它解决了你的问题,请将其标记为答案

更新2:

您的实际代码是:

    Dim ActivationUrl As String = Server.HtmlEncode("localhost:63774/ActivateAccount.aspx?userId=" & HttpUtility.UrlEncode(FetchUserId(txtEmailAddress.ToString)) & "&txtEmailAddress=" & HttpUtility.UrlEncode(txtEmailAddress.ToString) & "&ActivationCode=" & HttpUtility.UrlEncode(ActivationCode.ToString))

但是错误让我解释一下:

声明你的变量:Dim ActivationUrl as string没关系 然后建立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.UrlEncode(txtEmailAddress.ToString)'以这种方式传递一个值系统类型对象,它是一个文本框,用于传递您需要访问的文本框值.Text属性,如txtEmailAddress .Text

根据我上面的代码进行更改,它将起作用(如果您的程序正确)

**更新代码3 **

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

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