简体   繁体   English

使用C#发送邮件的条件

[英]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. 我需要一个条件(如果)来检查你是否连接到互联网,但我是新的C#,我不知道一个。

A good approach is using a try / catch block for this: 一个好的方法是使用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
}

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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