Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot send SMTP email from windows service on Win7

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 = "[email protected]";
                string emailCCAddresses = "[email protected]";

                //Send the email
                using (MailMessage mailMsg = new MailMessage())
                {
                    mailMsg.To.Add(emailAddresses);
                    mailMsg.From = new MailAddress("[email protected]");
                    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.

like image 470
PreethaA Avatar asked Nov 14 '22 08:11

PreethaA


1 Answers

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

like image 56
Alex Zhukovskiy Avatar answered Nov 16 '22 03:11

Alex Zhukovskiy