5

I am writing a Windows service using c# .NET 4.0 (my development workstation is Windows 7). The aim is to send an email from the service directly in case of errors during processing. I've included a code snippet to show what i am trying to achieve:

try
        {
                string emailAddresses = "me@sample.com";
                string emailCCAddresses = "you@sample.com";

                //Send the email
                using (MailMessage mailMsg = new MailMessage())
                {
                    mailMsg.To.Add(emailAddresses);
                    mailMsg.From = new MailAddress("winService@sample.com");
                    mailMsg.CC.Add(emailCCAddresses);
                    mailMsg.Subject = " Error Message ";
                    mailMsg.Body = DateTime.Now + " : Invalid File Encountered." ;

                    ////Creating the file attachment
                    using (Attachment data = new Attachment("C:\\users\\sample.xml", MediaTypeNames.Application.Octet))
                    {
                        //Add timestamp info for the file
                        ContentDisposition disposition = data.ContentDisposition;
                        disposition.ModificationDate = File.GetLastWriteTime("C:\\users\\sample.xml");
                        mailMsg.Attachments.Add(data);

                    SmtpClient emailClient = new SmtpClient("example.Sample.com", 25);
                    emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                    emailClient.UseDefaultCredentials = true;
                    emailClient.Send(mailMsg);
                    }
                }//end using

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

The issue i am facing is - the email option does not work from a win service on any windows 7 machine. However the exact same code will work on a Win XP machine perfectly fine. Caveat, this cannot be tested as a console app. It needs to be run as a service to see the behavior. I put the same code in a console application and it worked fine on my win 7 machine.

Additionally, i enabled the telnet client and server windows features and was able to send email via the command prompt successfully.

I tried a few things to try and isolate the cause (none worked) -

  • Setting the NetworkCredential explicitly and setting UseDefaultCredentials = false. emailClient.Credentials = new System.Net.NetworkCredential("username","pwd","Domain1");

  • changing the Log On As option of the service to be my userid and pwd

  • The From and To email addresses are authentic, not dummy addresses(in my real code that is!)

The only differences i can find is that the windows service is installed under the local system account. But changing the log on as should have caused it to use my authentication details/the credentials specified in the code. The IT guy in my office said the only difference he saw was that my message was sent as a relay(not sure what this means as the from/to and log on as accounts when updated to my login did not change the outcome)

the exception i see being caught is :

SMTP Exception thrown : System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions XXX.XXX.XXX.XXX XX at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)

Any ideas are appreciated!

I feel it has to do with a windows 7 security policy/feature and hopefully might be as simple as changing a default setting.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
PreethaA
  • 905
  • 12
  • 13
  • Do you have any firewall running? A quick Google for the message of the SocketException that's thrown initially ("An attempt was made to access a socket in a way forbidden by its access permissions...") suggests that a number of people who have experienced the same issue determined that their firewall software was preventing the service sending mail and solved it by disabling the firewall or adding an allow rule for their service in its configuration. – Iridium Mar 20 '12 at 06:59
  • i did think about that.. But i was able to send the smtp email via a console application(same code, just not a service) and via command prompt. Also, my coworker(same team and access rights) who ran the service on his windows xp machine was able to send email. We checked with IT and they tell us we are not blocked. – PreethaA Mar 20 '12 at 23:26
  • I would bet that it is the identity under which the service runs that is causing the issue. I do not know if they changed the default between XP and Win 7, but I know they did for IIS App pool. – Joshua Drake Apr 10 '12 at 20:39
  • i did enable telnet(it is disabled by default in win 7) for sending emails via command prompt.Once i installed the service, i changed the login to run as me, as opposed to the local system account...and still no emails from the service. – PreethaA Apr 11 '12 at 22:16
  • Was there an exception when you changed the "log on" parameter? – mj_ Aug 29 '12 at 18:44
  • I have the exact problem. Did you find any solution? – nils Dec 07 '12 at 14:53

2 Answers2

1

You can run service as current user. Just select option USER in service installer and it will work as current user. I got the same error today and I found this solution. I hope it will be helpful for anybody. enter image description here

Alex Zhukovskiy
  • 9,565
  • 11
  • 75
  • 151
0

I found it was the security policy on our new work laptops and the IT department refused to let us change it. Our test server doesn't have the same issue , of ourse it's not windows 7 either so I can't be 100% sure. Try sending email via command line to see if smtp is allowed from your pc.

The same code worked fine whn run on a win xp or windows server machine which didn't hav any restrictions

PreethaA
  • 905
  • 12
  • 13