我正在通过 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,如电子邮件已正确发送。
检查互联网连接是否存在以及是否开始发送邮件的常用方法是什么?