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

时间:2012-10-14 23:22:49

标签: vb.net

我正在通过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正确发送。

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

1 个答案:

答案 0 :(得分:0)

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

client.SendMailAsync(mail).ContinueWith(t=>HandleError(t.Exception), TaskContinuationOptions.OnlyOnFaulted)