0

I have the following code for sending mail and if you if you have a network connection it works perfectly.

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);

The probleme is: If you don't have a network connection and access this function, the application will crash. I don't want this to happen. I need a condition (if) to check if you are connected to internet, but I am new with C# and I don't know of one.

bobwah
  • 2,454
  • 4
  • 33
  • 49
AnDr3yy
  • 239
  • 2
  • 5
  • 16

2 Answers2

1

A good approach is using a try/catch block for this:

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
}
Gabe
  • 49,577
  • 28
  • 142
  • 181
  • The variabile 'e' is never used. Warning. How I can rid of with this Warning ? – AnDr3yy Aug 09 '12 at 15:51
  • the variable `e` is is the `exception` `object`, you can omit it if you're not going to use it. But, it contains information about the `exception` (stack trace, message, inner exceptions etc). If you look at my updated example, you can see that I can get the `exception` message from it. Doing that will remove the warning. – Gabe Aug 09 '12 at 15:52
1

If this is going to be an issue, you should probably check for a network connection before enabling your email routines.

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

That way, your user doesn't waste his time writing a big email before finding out the connection isn't there.

if (GetIsNetworkAvailable()) {
  // your code here
}