简体   繁体   中英

Condition for sending mail with C#

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.

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
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM