0

I am trying to send an email when the app runs into an error. In this example when the app can't mapp the network drive on the computer it is running.

This is my code:

private static void MapDrive()
    {
        try
        {
            Console.WriteLine("Mapping Network Drive");
            System.Diagnostics.Process.Start("net.exe", @"use w: \\server\CompanyData\W10 /user:domain\Administrator password").WaitForExit();
        }
        catch (Exception map)
        {
            Console.WriteLine(map);
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("server");
            mail.From = new MailAddress("email@email.com");
            mail.To.Add("user@email.com");
            mail.Subject = "Machine";
            mail.Body = "Could Not Map Network Drive" + System.Environment.MachineName.ToString();

            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);
            Console.ReadLine();
        }
    }

I think I am going the complete wrong way in doing this and need some one to point me in the right direction to get it to work.

Thanks

  • Your code looks fine to me. What error do you get? – Tomsen Dec 07 '20 at 06:46
  • @Tomsen, thats the thing, I don't get any errors neither am I receiving any emails? The SMTP details is definitely correct as I use them on my printers and they work 100% –  Dec 07 '20 at 06:49
  • Do you use Microsoft 365 or Office 365 SMTP or different SMTP? – user2250152 Dec 07 '20 at 07:11
  • You shouldn't write functional code in the catch scope. What if the `SmtpServer.Send(mail);` fails with an exception. You need another try/catch block. I would add the exception message to a queue and some other thread/task should send the mail. – Jeroen van Langen Dec 07 '20 at 07:24
  • A `try..catch` block only catches exceptions in the current thread. `System.Diagnostics.Process.Start` kicks off a new process, so your try..catch will only catch exceptions in starting the new process. Not in what that process does after it's been started. – Hans Kilian Dec 07 '20 at 07:27
  • https://stackoverflow.com/questions/8919/looking-for-best-practice-for-doing-a-net-use-in-c-sharp – mjwills Dec 07 '20 at 08:06
  • @HansKilian, that makes sense, but how do I go about achieving that? –  Dec 07 '20 at 11:59

0 Answers0