【问题标题】:How can I send an email with my vb.net code?如何使用我的 vb.net 代码发送电子邮件?
【发布时间】:2020-05-13 23:53:33
【问题描述】:

我正在使用 asp.net / vb.net。我想发一封电子邮件。我的代码没有按原样发送电子邮件。我想知道我在这里做错了什么。

我创建了一个名为 email.text 的文件,其中包含电子邮件模板。发送电子邮件的其余代码如下。我从代码中删除了个人信息。

我这样设置 SMTP 连接:

Private SMTPClientConnection As SmtpClient
Sub New()
    SMTPClientConnection = New SmtpClient
    SMTPClientConnection.Host = "HOSTHERE"
    SMTPClientConnection.Port = PORTHERE
    SMTPClientConnection.DeliveryMethod = SmtpDeliveryMethod.Network
End Sub

然后我创建了一个发送电子邮件的函数:

Private Shared Function SendEmail(ByVal emailUser As String, ByVal bodyMessage As List(Of String), ByVal priority As MailPriority) As Boolean
    Dim functionReturnValue As Boolean = False

    Try

        If Not String.IsNullOrWhiteSpace(emailUser) Then

            If Regex.IsMatch(emailUser, "^([a-zA-Z0-9]+([\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\.|[-]{1,2})[a-zA-Z0-9]+)*)\.[a-zA-Z]{2,6})$") Then

                Using SMTPClientConnection
                    Dim smtpMessage As MailMessage = New MailMessage()
                    Dim _with1 = smtpMessage
                    _with1.[To].Add(New MailAddress(emailUser))
                    _with1.From = New MailAddress("Test Email" & " <email@email.com>")
                    _with1.ReplyToList.Add(New MailAddress("email@email.com"))
                    _with1.Subject = "Test Email"
                    _with1.Priority = priority
                    Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(bodyMessage(0), Nothing, "text/html")
                    Dim plainView As AlternateView = AlternateView.CreateAlternateViewFromString(bodyMessage(1), Nothing, "text/plain")
                    _with1.AlternateViews.Add(plainView)
                    _with1.AlternateViews.Add(htmlView)
                    SMTPClientConnection.Send(smtpMessage)
                    Return True
                End Using
            Else
                Throw New SmtpException("Invalid email.")
            End If
        End If

    Catch ex As Exception
    End Try

    Return functionReturnValue
End Function

我在这里的代码中使用了这个函数:

            Dim plainBody As String = File.ReadAllText(HttpContext.Current.Server.MapPath("email.txt"))
            plainBody = plainBody.Replace("%Name%", emailName)

            Dim emailBody As List(Of String) = New List(Of String)(New String() {plainBody})
            SendEmail("email@email.com", emailBody, MailPriority.Normal)

【问题讨论】:

  • 好吧。开始删除那个空的 try catch 块。如果出现错误,您将永远看不到它,也无法告诉我们这里发生了什么错误。
  • 您是否首先测试了您的连接-主机和端口名称是否正确?
  • @Steve @salsinga 是的,主机和端口是正确的。我相信我的问题是Using SMTPClientConnection,它显示的是Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class

标签: asp.net vb.net smtp smtpclient


【解决方案1】:

编译器错误信息很清楚。变量 SmtpClientConnection 是一个实例变量(它作为不同的实体存在于任何声明的类实例中)但您试图在 Shared 方法中使用(该方法存在没有类实例)。在这种方法中你不能使用实例变量,因为你没有一个实例可以让方法从中选择变量值并使用它。

解决方案可能是从方法中删除 Shared 关键字,然后,每当您要调用该方法时,您需要创建实例变量 SmtpClientConnection 已初始化并准备好在以下对 SendMail 方法的调用中使用。

但是,您仍然可以使用 Shared 方法,但应该删除实例变量并在 SmtpClient 方法中创建它:

Private Shared Function SendEmail(ByVal emailUser As String, ByVal bodyMessage As List(Of String), ByVal priority As MailPriority) As Boolean
    Dim functionReturnValue As Boolean = False

    Try

        If Not String.IsNullOrWhiteSpace(emailUser) Then

            If Regex.IsMatch(emailUser, "^([a-zA-Z0-9]+([\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\.|[-]{1,2})[a-zA-Z0-9]+)*)\.[a-zA-Z]{2,6})$") Then


               Dim SMTPClientConnection As SmtpClient = New SmtpClient
               SMTPClientConnection.Host = "HOSTHERE"
               SMTPClientConnection.Port = PORTHERE
               SMTPClientConnection.DeliveryMethod = SmtpDeliveryMethod.Network                
               Using SMTPClientConnection
                    Dim smtpMessage As MailMessage = New MailMessage()
                    ......
                    SMTPClientConnection.Send(smtpMessage)
                    Return True
                End Using
            Else
                Throw New SmtpException("Invalid email.")
            End If
        End If

    Catch ex As Exception
       ' No point in catching an exception and doing nothing here.
       ' You can log the exception somewhere and then throw it again
       LogException(ex)
       Throw
       ' or just remove the try/catch block.
    End Try
    Return functionReturnValue
End Function

通过这种方式,变量仅在需要时创建,并在 using 语句结束时销毁。还要注意与 Try/Catch 块相关的 cmets。

【讨论】:

    猜你喜欢
    • 2010-12-24
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多