Click here to Skip to main content
15,396,239 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I create a Python script to count the idle time in windows computer and write it down in text file, I wanted to make this because the user leave the shop for a while and come back without permission. so i wanted to add in my script function to send the that text to my email at 12:00AM everyday but i don't know how. this is my code and i want to know if there is a problem with this code .... i'm new in Python

What I have tried:

import ctypes, ctypes.wintypes
from time import strftime
from datetime import datetime
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


class LASTINPUTINFO(ctypes.Structure):
    _fields_ = [
      ('cbSize', ctypes.wintypes.UINT),
      ('dwTime', ctypes.wintypes.DWORD),
      ]

PLASTINPUTINFO = ctypes.POINTER(LASTINPUTINFO)

user32 = ctypes.windll.user32
GetLastInputInfo = user32.GetLastInputInfo
GetLastInputInfo.restype = ctypes.wintypes.BOOL
GetLastInputInfo.argtypes = [PLASTINPUTINFO]

kernel32 = ctypes.windll.kernel32
GetTickCount = kernel32.GetTickCount
Sleep = kernel32.Sleep

def wait_until_idle(idle_time=60):

    idle_time_ms = int(idle_time*1000)
    liinfo = LASTINPUTINFO()
    liinfo.cbSize = ctypes.sizeof(liinfo)
    while True:
        GetLastInputInfo(ctypes.byref(liinfo))
        elapsed = GetTickCount() - liinfo.dwTime
        if elapsed>=idle_time_ms:
            break
        Sleep(idle_time_ms - elapsed or 1)


def wait_until_active(tol=5):

    liinfo = LASTINPUTINFO()
    liinfo.cbSize = ctypes.sizeof(liinfo)
    lasttime = None
    delay = 1 # ms
    maxdelay = int(tol*1000)
    while True:
        GetLastInputInfo(ctypes.byref(liinfo))
        if lasttime is None: lasttime = liinfo.dwTime
        if lasttime != liinfo.dwTime:
            break
        delay = min(2*delay, maxdelay)
        Sleep(delay)

def start():
    string = strftime('%I:%M:%S %p ')
    string2 = strftime('%A  %d-%b-%Y')
    new_line = '\n'
    print("Waiting for 10 Second of no user input...")
    wait_until_idle(10)
    user32.MessageBeep(0)
    with open("d:\idle.txt", "a") as f:
        f.write(new_line + string + string2 + ' Start')

start()
def end():
    print("Ok. Now, do something!")
    wait_until_active(1)
    user32.MessageBeep(0)
    now = datetime.now()
    string = now.strftime('%I:%M:%S %p ')
    string2 = now.strftime('%A  %d-%b-%Y')
    new_line = '\n'
    with open("d:\idle.txt", "a") as f:
        f.write(new_line + string + string2 + ' End')

end()

def send_email():
    from_address = 'xxxx@xxxxxx.com'
    sender_pass = 'xxxxxxxxx'
    to_address = 'xxxx@xxxxxx.com'
    subject = 'anything '
    content = 'anything2'
    body = 'anything3'
    msg = MIMEMultipart()
    msg['From'] = from_address
    msg['To'] = to_address
    msg['Subject'] = subject
    body = MIMEText(content, 'plain')
    msg.attach(body)
    filename = 'D:\Idle.txt'
    with open(filename, 'r') as f:
        attachnemt = MIMEApplication(f.read(), Name=basename(filename))
        attachnemt['contant-Disposition '] = 'attackment; filename="{}'.format(basename(filename))
    msg.attach(attachnemt)
    server = smtplib.SMTP('mail.xxxxxxx.com', 587)
    server.login(from_address, '************')
    server.send_message(msg, from_addr=from_address, to_addrs=[to_address])
    print('sent')
send_email()
while True:
    duration1 = start()
    duration2 = end()
    email = send_email()
    print(duration1)
    print(duration2)
    print(email)
Posted
Updated 18-Jul-22 9:40am
Comments
Richard MacCutchan 25-Jun-22 5:41am
   
The datetime.now function returns the current time, so you just need to check if it has passed the time at which the email should be sent.
Mohamed Hussein 2022 25-Jun-22 6:00am
   
how to do it ?
Richard MacCutchan 25-Jun-22 6:19am
   
How to do what? If you have a technical question then please provide proper details.

1 solution

If you want to send email at specific time, you need to schedule that job.
You can use: schedule · PyPI[^]

Python
import schedule
import time

def job():
    print("I'm working...")

schedule.every().day.at("23:59").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)


Another module is: sched — Event scheduler — Python 3.10.5 documentation[^]
   
Comments
0x01AA 18-Jul-22 15:50pm
   
Holy whatever.... If every small job will be handled like this (e.g. a windows service) windows will be down soon:-)
I think for tasks like this the operating system's task scheduling should be used.

No vote from here.
Maciej Los 18-Jul-22 17:28pm
   
Yes, windows scheduler can be used for such of purposes, Bruno.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900