我正在使用SMTP服务器发送电子邮件。
我想在SMTP服务器关闭或电子邮件未送达时收到错误消息
使用DeliveryNotificationOptions.OnFailure,我收到一封电子邮件,表明该电子邮件尚未发送
我想得到一个错误。这可能吗?
我如何检查SMTP是否正在运行?
以下是我使用的代码:
Dim serverName As String = ""
Dim mailSenderInstance As SmtpClient = Nothing
Dim AnEmailMessage As New MailMessage
Dim sendersEmail As String = ""
Try
serverName = GetServerName("EMAIL_SERVER")
mailSenderInstance = New SmtpClient(serverName, 25)
sendersEmail = GetSendersEmail(msUserName)
AnEmailMessage.From = New MailAddress(sendersEmail)
'MAIL DETAILS
AnEmailMessage.Subject = "New Email"
AnEmailMessage.Body = "The Message"
AnEmailMessage.To.Add(anEmailAddress)
' Delivery notifications
AnEmailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
mailSenderInstance.UseDefaultCredentials = True 'False
mailSenderInstance.Send(AnEmailMessage)
Catch ex As System.Exception
MessageBox.Show(ex.ToString)
Finally
AnEmailMessage.Dispose()
mailSenderInstance.Dispose()
End Try
答案 0 :(得分:0)
在SMTP声明周围添加另一个try catch块
try
mailSenderInstance = New SmtpClient(serverName, 25)
catch ex as exception
msgbox( "Error creating SMTP connection: " & ex.message)
end try
问候
答案 1 :(得分:0)
好的,您想知道SMTP状态。 SMTP作为服务运行。我已经为您编写了一个函数来了解系统中任何服务的状态。在项目中添加对“System.ServiceProcess”的引用。
''response: -1 = service missing, 0 = stopped or stopping, 1 = running
imports System.ServiceProcess ''add this at top
Private Function GetServiceStatus(ByVal svcName As String) As Integer
Dim retVal As Integer
Dim sc As New ServiceController(svcName)
Try
If sc.Status.Equals(ServiceControllerStatus.Stopped) Or sc.Status.Equals(ServiceControllerStatus.StopPending) Then
retVal = 0
Else
retVal = 1
End If
Catch ex As Exception
retVal = -1
End Try
Return retVal
End Function
像这样使用它:
'' use taskManager to figure correct service name
dim svStatus as integer = GetServiceStatus("SMTP")
if svStatus <> 1 then
msgbox("Service not running or absent")
else
''write your send mail code here
end if
希望这会对你有所帮助