txt2mail.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/env python3
  2. import os, shutil, smtplib, sys
  3. from inotify_simple import INotify, flags
  4. from email.mime.text import MIMEText
  5. # Define and create folders if they don't exist
  6. prep = 'mail/1-prep/'
  7. ready = 'mail/2-ready/'
  8. done = 'mail/3-done/'
  9. os.makedirs(prep, exist_ok=True)
  10. os.makedirs(ready, exist_ok=True)
  11. os.makedirs(done, exist_ok=True)
  12. # Register inotify event for files moved to the ready folder
  13. inotify = INotify()
  14. watch_flags = flags.MOVED_TO
  15. wd = inotify.add_watch(ready, watch_flags)
  16. print('Watching for files moved to :' + os.path.dirname(os.path.realpath(__file__)) + '/' + ready)
  17. # Get events and take action
  18. while True:
  19. events = inotify.read()
  20. for event in events:
  21. # Report file found and read lines
  22. print(ready + event.name)
  23. lines = open(ready + event.name).readlines()
  24. # Compose e-mail
  25. msg = MIMEText(''.join(lines[1:]))
  26. msg['Subject'] = ''.join(lines[0]).strip()
  27. msg['From'] = os.environ['MAIL_FROM']
  28. msg['To'] = os.environ['MAILTO']
  29. # Send e-mail
  30. s = smtplib.SMTP(host=os.environ['MAIL_RELAY_HOST'], port=os.environ['MAIL_PORT'])
  31. # s.set_debuglevel(1)
  32. s.starttls()
  33. s.login(os.environ['MAIL_USER'], os.environ['MAIL_PASSWORD'])
  34. s.sendmail(os.environ['MAIL_FROM'], os.environ['MAILTO'], msg.as_string())
  35. s.quit()
  36. # Move file to the "done" folder
  37. shutil.move(ready + event.name,done)