我正在使用 C# 发送电子邮件。当互联网可用时它工作正常,但当互联网连接不可用时它会一次又一次返回异常消息并停止执行。如果连接不可用,如何忽略发送电子邮件并继续执行, 或任何其他合适的方法来做到这一点..
while (true)
{
try
{
Thread.Sleep(50);
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("mymail");
mail.To.Add("mymail");
mail.Subject = "data - 1";
mail.Body = "find attachement";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(filepath);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail", "mypassword");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch (Exception)
{
MessageBox.Show("Internet Connection is not found");
}
}
最佳答案
任何依赖于重复尝试的解决方案都可能最终无限循环。
您的代码正在同步发送电子邮件,为什么不send asynchronously使用pickup directory
这会将电子邮件放入 SMTP 接收目录,并且 SMTP 服务器将通过在可配置的时间段内重试来处理暂时的网络问题。
关于c# - 如何忽略发送电子邮件方法并继续执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33390751/