【发布时间】: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