-2

如果有人能告诉我我是否走在正确的轨道上,我将不胜感激......基本上,我有一个需要为我的应用程序运行的网络服务,我已将其放入 try catch,如果尝试失败我希望 catch 向我发送一封包含异常详细信息的电子邮件。

try
{
    // run webservice here
}
catch (Exception ex)
{
    string strTo = "scott@...";
    string strFrom = "web@...";
    string strSubject = "Webservice Not Run";
    SmtpMail.SmtpServer = "thepostoffice";

    SmtpMail.Send(strFrom, strTo, strSubject, ex.ToString());
}
4

3 回答 3

4

是的,但是您最好将异常处理程序包装在某种记录器中,或者使用现有的记录器,例如Log4NetNLog

于 2013-03-11T13:37:41.973 回答
1

发生异常时发送电子邮件的快速简便方法可以这样完成:

        SmtpClient Server = new SmtpClient();
        Server.Host = ""; //example: smtp.gmail.com
        Server.Port = ; //example: 587 if you're using gmail
        Server.EnableSsl = true; //If the smtp server requires it

        //Server Credentials
        NetworkCredential credentials = new NetworkCredential();
        credentials.UserName = "youremail@gmail.com";
        credentials.Password = "your password here";
        //assign the credential details to server
        Server.Credentials = credentials;

        //create sender's address
        MailAddress sender = new MailAddress("Sender email address", "sender name");

        //create receiver's address
        MailAddress receiver = new MailAddress("receiver email address", "receiver name");

        MailMessage message = new MailMessage(sender, receiver);
        message.Subject = "Your Subject";
        message.Body = ex.ToString();
        //send the email
        Server.Send(message); 
于 2020-08-13T23:14:49.423 回答
-1

是的,如果您不想使用任何记录器工具,这是正确的方法。您可以为您的公共类之一创建函数 SendMail(stringExceptionoin),然后从每个 catch 块调用此函数

于 2013-03-11T13:38:13.207 回答