0

我有以下用于发送邮件的代码,如果您有网络连接,它可以完美运行。

MailMessage oMail = new MailMessage(new MailAddress("andr3yy.design@yahoo.com"), new MailAddress(setare[0].email));
        oMail.Subject = "Subject";
        oMail.Body = "Body";
        SmtpClient oSmtp = new SmtpClient();
        oSmtp.Host = "smtp.mail.yahoo.com";          
        oSmtp.Credentials = new NetworkCredential("andr3yy.design", "password");
        oSmtp.EnableSsl = false;
        oSmtp.Port = 587;
        oSmtp.Send(oMail);

问题是:如果您没有网络连接并访问此功能,应用程序将崩溃。我不希望这种情况发生。我需要一个条件(如果)来检查你是否连接到互联网,但我是 C# 新手,我不知道。

4

2 回答 2

1

如果这将成为一个问题,您可能应该在启用电子邮件例程之前检查网络连接。

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

这样,您的用户就不会在发现连接不存在之前浪费时间写一封大电子邮件。

if (GetIsNetworkAvailable()) {
  // your code here
}
于 2012-08-09T15:50:02.083 回答
1

一个好的方法是为此使用try/块:catch

MailMessage oMail = new MailMessage(new MailAddress("andr3yy.design@yahoo.com"), new MailAddress(setare[0].email)){
   Subject = "Subject",
   Body = "Body"
};

SmtpClient oSmtp = new SmtpClient() {
   Host = "smtp.mail.yahoo.com",          
   Credentials = new NetworkCredential("andr3yy.design", "password"),
   EnableSsl = false,
   Port = 587
};

try{
        oSmtp.Send(oMail);
} 
catch(Exception e) { 

    string message = e.Message;
    // this will handle no connection to the internet, along with other possible exceptions
}
于 2012-08-09T15:46:15.197 回答