Я разработал Python Windows Service, который отправляет электронное письмо каждые 5 секунд. Он работает в режиме отладки, устанавливается и после запуска показывает состояние «Работает», но в отличие от режима отладки служба Windows не отправляет никаких писем. Я прошел через Интернет, но не смог найти, как заставить эту службу Windows работать на самом деле.
Код:
import win32service
import win32serviceutil
import win32event
import servicemanager
import sys
import logging
# -------------------------------------------- Begin
import psycopg2
import pandas as pd
import win32com.client as win32
mailSenderProperties = {
"reciversList": ['ashishjain@gmail.com']
}
outlook = win32.Dispatch('outlook.application')
def sendMail(recipients, subject, HTMLBody):
for recipient in recipients:
mail = outlook.CreateItem(0)
mail.To = recipient
mail.Subject = subject
# mail.Body = 'Message body'
mail.HTMLBody = HTMLBody
mail.Send()
def run():
msg_text = "<p>Your Service request XYZ has been accepted and is under process. You will be intimated through Email once the service request is completed. Details are as mentioned below for your reference: </p>"
sendMail(mailSenderProperties['reciversList'], 'Subject', msg_text)
# -------------------------------------------- End
class PySvcV11(win32serviceutil.ServiceFramework):
# you can NET START/STOP the service by the following name
_svc_name_ = "PythonMailSenderServiceV11"
# this text shows up as the service name in the Service
# Control Manager (SCM)
_svc_display_name_ = "PythonMailSenderServiceV11"
# this text shows up as the description in the SCM
_svc_description_ = "This service sends mail via Outlook"
logging.basicConfig(filename="C:/Users/Rajeev/Desktop/MailSenderSvcV11.log", format='%(asctime)s %(message)s', filemode='w')
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self,args)
# create an event to listen for stop requests on
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
logging.debug("Exiting __init__")
# core logic of the service
def SvcDoRun(self):
logging.debug("Entering SvcDoRun")
rc = None
f = open('C:/Users/Rajeev/Desktop/hello.txt', 'w+')
# if the stop event hasn't been fired keep looping
while rc != win32event.WAIT_OBJECT_0:
run()
f.write('TEST DATA\n')
f.flush()
# block for 5 seconds and listen for a stop event
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
f.write('SHUTTING DOWN\n')
f.close()
# called when we're being shut down
def SvcStop(self):
# tell the SCM we're shutting down
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# fire the stop event
win32event.SetEvent(self.hWaitStop)
if __name__ == '__main__':
logging.debug("len(sys.argv): " + str(len(sys.argv)))
logging.debug("sys.argv: " + str(sys.argv))
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(PySvcV11)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(PySvcV11)