0

我正在通过 VB.NET 发送电子邮件,如显示的代码:

    Dim retval As Integer
    Dim attachment As System.Net.Mail.Attachment = Nothing
    If fileName <> "" Then
        attachment = New System.Net.Mail.Attachment(fileName)
    End If

    Dim client As New SmtpClient()
    With client
        .EnableSsl = True
        .Host = smtpServerAddress
        .Port = 587
        .DeliveryMethod = SmtpDeliveryMethod.Network
        .UseDefaultCredentials = False
        .Credentials = New NetworkCredential(FromEmailId, password)
        AddHandler .SendCompleted, AddressOf SendCompletedCallback
    End With

    Dim mail = New MailMessage(FromEmailId, toEmailId)
    With mail
        .Priority = MailPriority.High
        .Subject = subject
        .SubjectEncoding = System.Text.Encoding.UTF8
        .IsBodyHtml = False
        If fileName <> "" Then
            .Attachments.Add(attachment)
        End If
        .Body = msgBody
        .BodyEncoding = System.Text.Encoding.UTF8
    End With

    Try
        client.SendAsync(mail, "")
        retval = 1
    Catch ex As Exception
        retval = 0
        MsgBox(ex.Message, MsgBoxStyle.Critical)
    End Try

    Return retval

这部作品很好。问题只是如果我没有连接到互联网,我的 Try/Catch 块不会按预期做出反应。我知道邮件没有发出的唯一方法是我没有收到来自回调的消息,这可能需要很长时间。此外,我从功能返回 1,如电子邮件已正确发送。

检查互联网连接是否存在以及是否开始发送邮件的常用方法是什么?

4

1 回答 1

0

如果您想捕获从 SmtpClient 抛出的所有异常,您可以同步发送邮件。如果您更喜欢异步方式,请使用SendMailAsync返回 Task 实例,您可以在该实例上调用 ContinueWith 来设置错误处理程序:

client.SendMailAsync(mail).ContinueWith(t=>HandleError(t.Exception), TaskContinuationOptions.OnlyOnFaulted)
于 2012-10-14T23:34:37.467 回答