txt2mail.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. base = '/opt/txt2mail/var/'
  7. prep = base + '1-prep/'
  8. ready = base + '2-ready/'
  9. done = base + '3-done/'
  10. os.makedirs(prep, exist_ok=True)
  11. os.makedirs(ready, exist_ok=True)
  12. os.makedirs(done, exist_ok=True)
  13. # Register inotify event for files moved to the "ready" folder
  14. inotify = INotify()
  15. watch_flags = flags.MOVED_TO
  16. wd = inotify.add_watch(ready, watch_flags)
  17. print('Watching for files moved to :' + os.path.dirname(os.path.realpath(__file__)) + '/' + ready)
  18. # Get events and take action
  19. while True:
  20. events = inotify.read()
  21. for event in events:
  22. # Report file found and read lines
  23. print(ready + event.name)
  24. lines = open(ready + event.name).readlines()
  25. # Compose e-mail
  26. msg = MIMEText(''.join(lines[1:]))
  27. msg['Subject'] = ''.join(lines[0]).strip()
  28. msg['From'] = os.environ['MAIL_FROM']
  29. msg['To'] = os.environ['MAILTO']
  30. # Send e-mail
  31. s = smtplib.SMTP(host=os.environ['MAIL_RELAY_HOST'], port=os.environ['MAIL_PORT'])
  32. # s.set_debuglevel(1)
  33. s.starttls()
  34. s.login(os.environ['MAIL_USER'], os.environ['MAIL_PASSWORD'])
  35. s.sendmail(os.environ['MAIL_FROM'], os.environ['MAILTO'], msg.as_string())
  36. s.quit()
  37. # Move file to the "done" folder
  38. shutil.move(ready + event.name,done)