I'm new to programming.
This is my first time to ask a question, so I'm sorry if the question is bad.
windows10 Pro ver.1909
Python 3.7.7

・ I want to achieve
When the computer starts up
"Always monitor the folder and send an email when an xlsx file is created"
Run the program.

·current situation
Using Python watchdog, I am writing a program that constantly monitors the specified folder and sends gmail when an xlsx file is created in that folder.
If i run the program in the IDE or command prompt, the result will be as intended.
However, I wanted the program to run automatically when the computer started, but it didn't work and I asked a question here.
Thank you.

Error message
Corresponding source code
import time
import os
import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate
from watchdog.events import FileSystemEventHandler
from watchdog.observers.polling import PollingObserver
FROM_ADDRESS ='****@gmail.com'
TO_ADDRESS ='**** @ ****'
BCC =''
SUBJECT ='****'
BODY ='****'
def create_message (from_addr, to_addr, bcc_addrs, subject, body):
    msg = MIMEText (body)
    msg ['Subject'] = subject
    msg ['From'] = from_addr
    msg ['To'] = to_addr
    msg ['Bcc'] = bcc_addrs
    msg ['Date'] = formatdate ()
    return msg
def send (from_addr, to_addrs, msg):
    smtpobj = smtplib.SMTP_SSL ('smtp.gmail.com', 465, timeout = 10)
    smtpobj.login (FROM_ADDRESS, MY_PASSWORD)
    smtpobj.sendmail (from_addr, to_addrs, msg.as_string ())
    smtpobj.close ()
BASEDIR = "C: \\ sample"
def getext (filename):
    return os.path.splitext (filename) [-1] .lower ()
class ChangeHandler (FileSystemEventHandler):
    def on_created (self, event):
        if event.is_directory:
        if getext (event.src_path) in ('.xlsx'):
            if __name__ =='__main__':
                to_addr = TO_ADDRESS
                subject = SUBJECT
                body = BODY
                msg = create_message (FROM_ADDRESS, to_addr, BCC, subject, body)
                send (FROM_ADDRESS, to_addr, msg)
if __name__ in'__main__':
    while 1:
        event_handler = ChangeHandler ()
        observer = PollingObserver ()
        observer.schedule (event_handler, BASEDIR, recursive = True)
        observer.start ()
        try: try:
            while True:
                time.sleep (1)
        except KeyboardInterrupt:
            observer.stop ()
        observer.join ()
What I tried

1. I put the program in the startup folder (shell: startup) but it didn't run.
2. I set the task start trigger of the task scheduler to "at startup", but the task is completed and I cannot always monitor the file.

Supplementary information (FW/tool version, etc.)
  • Answer # 1

    In task scheduler
    The contents of temp11119.bat will not work if it is Python code

    Inside the bat is the location of the python file and the target file name.py

    Example: python c: \ py \ pg.py