当出现异常时发送SMTP邮件

本文关键字:SMTP 邮件 异常 | 更新日期: 2023-09-27 18:03:24

如果有人能告诉我我是否在正确的轨道上,我会很感激。基本上,我有一个webservice,我需要为我的应用程序运行,我已经把它放入一个try catch中,如果try失败,我希望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());
}

当出现异常时发送SMTP邮件

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

在异常发生时发送电子邮件的一种快速简便的方法如下:

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

是的,这是正确的方式,如果您不想使用任何记录器工具。您可以创建函数SendMail(string exception)到您的一个公共类,然后从每个捕获块

调用该函数