如果我使用Send方法,我可以按预期处理任何异常。
Try
'Synchronous method
OutputStatus("Sending message, please wait")
smtp.Send(mail)
Catch smtpEx As SmtpCommandException
If smtpEx.ErrorCode = SmtpErrorCode.RecipientNotAccepted Then
OutputStatus("Unable to send message to: " & smtpEx.Mailbox.Address)
ElseIf smtpEx.ErrorCode = SmtpErrorCode.UnexpectedStatusCode Then
OutputStatus("Unable to send message: " & smtpEx.Message)
....
End If
但是,如果我使用SendAsync方法,我不会收到异常,并且MessageSent事件处理程序也不会触发(所以我被困在Do While循环中(。如果消息正常,则事件处理程序工作正常。
AddHandler smtp.MessageSent, AddressOf SMTPMessageSent
mbSendingMessage = True
Try
smtp.SendAsync(mail)
Do While mbSendingMessage
Application.DoEvents()
Loop
Catch ex As Exception
OutputStatus("Error sending, see GWMailer.err")
End Try
....
Private Sub SMTPMessageSent(sender As Object, e As MailKit.MessageSentEventArgs)
mbSendingMessage = False
End Sub
非常感谢您的帮助。感谢
为什么不直接这么做呢?
Await smtp.SendAsync(mail)
有关如何在VB.NET中处理异步API的更多信息,请查看以下文档:https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/await-operator