【问题标题】:Activation Email/Link Not Working激活电子邮件/链接不起作用
【发布时间】:2014-06-11 20:22:23
【问题描述】:

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

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 功能不再起作用。请有人帮忙! :(

【问题讨论】:

  • 只需对您的工作版本进行备份。
  • 除非我错过了,否则您(期望)如何收到错误消息(回复:ASP.Net 中的MsgBox 是什么,catch 似乎已被注释掉)?
  • catch as ex 异常被注释掉,因为它不是必需的。写入数据库的 SQL 命令工作正常。它写正确,唯一的问题是电子邮件没有发送,我上次尝试时,电子邮件中提供的激活链接也不起作用,它只是重定向到一个空白页面。
  • 好的,我又收到了电子邮件,但是来自电子邮件链接的页面仍然没有显示任何内容,完全空白。

标签: asp.net sql vb.net email activation


【解决方案1】:

嗨 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") 一样使用来获取该特定参数的值,但在您检查未传递到链接中的键的情况下。请注意,您只设置了 3 个键,分别是

用户ID

txt电子邮件地址

激活码

请求查询字符串中没有“UMaryEmail”键

另外一个重要的东西永远不要在查询字符串数据库字段中传递:) 使用不反映数据库字段的幻想名称或短名称

示例:

用户ID => uid

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

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

现在激活页面问题,当您尝试检查您的值时使用 if 语句检查用户 ID 键和 UMaryEmail,其中用户 ID 可以匹配,因为它存在于查询字符串中,但 UmaryEmail 不在您尚未提供的 request.querystring 中所以如果失败并且页面中没有显示任何内容。

在这里你的激活子重新访问了一些 cmets 以便更好地理解:

  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

【讨论】:

  • 恐怕我不明白你想对“UMaryEmail”键说什么。它被定义为上面注册/注册页面下的参数之一。在 SQL 数据库中,电子邮件地址列被命名为“UMaryEmail”,这就是我在 if 语句查询中使用该名称的原因,而不是 emailaddress 或 txtEmailAddress。我用那个名字错了吗?我将 server.htmlencode 更改为 httputility.urlEncode 但我太缺乏经验,无法理解这两个命令之间的区别。感谢您的回复。
  • 几分钟后看看帖子,我会给你看一些例子:)来帮助你
  • 我已经更新了我的代码,对您的代码进行了一些更改,以便帮助您。:)
  • 好的,我尝试了您的 ActivateMyAccount,但由于某种原因我没有收到电子邮件。我检查了我的垃圾邮件,但找不到。
  • @FlummoxedUser 您说:好的,我尝试了您的 ActivateMyAccount,但由于某种原因我没有收到电子邮件。我对您的激活代码进行了一些更改,所以如果您邮件未发送您是否必须检查上面的代码。调试您的应用程序以检查是否引发了异常
猜你喜欢
  • 2014-10-20
  • 1970-01-01
  • 1970-01-01
  • 2020-02-10
  • 2014-08-17
  • 2014-03-16
  • 2016-07-05
  • 2011-02-14
  • 2021-04-28
相关资源
最近更新 更多