Application which monitors a folder and sends each file via mail
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

file2mail.py 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 report
  10. import time
  11. LOCK_FILE = os.path.join(config.TARGET_FOLDER, "lock")
  12. PID = os.getpid()
  13. logger = logging.getLogger('root')
  14. report.stdoutLoggingConfigure(log_name_lvl=[('root', config.LOG_LEVEL), ])
  15. if __name__ == "__main__":
  16. while True:
  17. # Check if LOCK_FILE EXISTS
  18. if not os.path.exists(LOCK_FILE):
  19. # Create LOCK_FILE
  20. with open(LOCK_FILE, 'w') as fh:
  21. fh.write(str(PID))
  22. logger.debug("Creating lock-file %s with PID %d", LOCK_FILE, PID)
  23. # Read LOCK_FILE content
  24. with open(LOCK_FILE, 'r') as fh:
  25. lf_pid = json.loads(fh.read())
  26. # Check if LOCK_FILE has my PID
  27. if lf_pid == PID:
  28. # Scan for files to send
  29. for filename in fstools.filelist(config.TARGET_FOLDER):
  30. # Exclude LOCK_FILE
  31. if filename != LOCK_FILE:
  32. logger.info("Found %s to send via E-Mail to %s.", filename, config.SEND_TO)
  33. # Send File as E-Mail
  34. try:
  35. mail.send_mail(
  36. config.SEND_FROM,
  37. config.SEND_TO,
  38. "Gesanntes Dokument - %s" % os.path.basename(filename),
  39. "Hier ist das gescannte Dokument vom Scanner in Buchen:",
  40. files=[filename],
  41. server=config.SMTP_SERVER,
  42. username=config.SMTP_USER,
  43. password=config.SMTP_PASSWORD
  44. )
  45. except Exception:
  46. logger.exception("Exception while sending an E-Mail")
  47. else:
  48. # Remove file
  49. logger.debug("Removing file %s", filename)
  50. os.remove(filename )
  51. # Remove LOCK_FILE
  52. logger.debug("Removing lock-file %s", LOCK_FILE)
  53. os.remove(LOCK_FILE)
  54. else:
  55. logger.warning("LOCK_FILE has PID %d and this proces %d. No action!", lf_pid, PID)
  56. else:
  57. logger.warning("LOCK_FILE %s already exists. No action!", LOCK_FILE)
  58. time.sleep(60)