Application which monitors a folder and sends each file via mail
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. import config
  4. import fstools
  5. import json
  6. import logging
  7. import mail
  8. import os
  9. import psutil
  10. import report
  11. import time
  12. LOCK_FILE = os.path.join(config.TARGET_FOLDER, "lock")
  13. PID = os.getpid()
  14. logger = logging.getLogger('root')
  15. report.stdoutLoggingConfigure(log_name_lvl=[('root', config.LOG_LEVEL), ])
  16. def has_handle(fpath):
  17. for proc in psutil.process_iter():
  18. try:
  19. for item in proc.open_files():
  20. if fpath == item.path:
  21. return True
  22. except Exception:
  23. pass
  24. return False
  25. if __name__ == "__main__":
  26. while True:
  27. # Check if LOCK_FILE EXISTS
  28. if not os.path.exists(LOCK_FILE):
  29. # Create LOCK_FILE
  30. with open(LOCK_FILE, 'w') as fh:
  31. fh.write(str(PID))
  32. logger.debug("Creating lock-file %s with PID %d", LOCK_FILE, PID)
  33. # Read LOCK_FILE content
  34. with open(LOCK_FILE, 'r') as fh:
  35. lf_pid = json.loads(fh.read())
  36. # Check if LOCK_FILE has my PID
  37. if lf_pid == PID:
  38. # Scan for files to send
  39. for filename in fstools.filelist(config.TARGET_FOLDER):
  40. # Exclude LOCK_FILE
  41. if filename != LOCK_FILE and not has_handle(filename):
  42. logger.info("Found %s to send via E-Mail to %s.", filename, config.SEND_TO)
  43. # Send File as E-Mail
  44. try:
  45. mail.send_mail(
  46. config.SEND_FROM,
  47. config.SEND_TO,
  48. "Gesanntes Dokument - %s" % os.path.basename(filename),
  49. "Hier ist das gescannte Dokument vom Scanner in Buchen:",
  50. files=[filename],
  51. server=config.SMTP_SERVER,
  52. username=config.SMTP_USER,
  53. password=config.SMTP_PASSWORD
  54. )
  55. except Exception:
  56. logger.exception("Exception while sending an E-Mail")
  57. else:
  58. # Remove file
  59. logger.debug("Removing file %s", filename)
  60. os.remove(filename)
  61. # Remove LOCK_FILE
  62. logger.debug("Removing lock-file %s", LOCK_FILE)
  63. os.remove(LOCK_FILE)
  64. else:
  65. logger.warning("LOCK_FILE has PID %d and this proces %d. No action!", lf_pid, PID)
  66. else:
  67. logger.warning("LOCK_FILE %s already exists. No action!", LOCK_FILE)
  68. time.sleep(60)