将目录更新收集到一封电子邮件中

时间:2017-04-03 08:03:29

标签: python email directory updates

我目前有一个python脚本通知我通过电子邮件更改目录。但是,因为我收到有关OneNote文档更新的通知(一旦进行更改后自动保存),我会在编辑文档时发送多封电子邮件。

我希望在10分钟内发生的所有更新都会通过一封电子邮件发送给我,但我不知道该怎么做。

这是我的代码:

    import os
import win32file
import win32con
import win32com.client

o   = win32com.client.Dispatch("Outlook.Application")


ACTIONS = {
  1 : "Created",
  2 : "Deleted",
  3 : "Updated",
  4 : "Renamed from something",
  5 : "Renamed to something"
}

FILE_LIST_DIRECTORY = 0x0001

path_to_watch =r"\\FILE-LUX12-03\lux12_Translation\Translation\jllevent\QA_threads"
hDir = win32file.CreateFile (
  path_to_watch,
  FILE_LIST_DIRECTORY,
  win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
  None,
  win32con.OPEN_EXISTING,
  win32con.FILE_FLAG_BACKUP_SEMANTICS,
  None
)
while 1:

  results = win32file.ReadDirectoryChangesW (
    hDir,
    1024,
    True,
    win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
     win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
     win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
     win32con.FILE_NOTIFY_CHANGE_SIZE |
     win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
     win32con.FILE_NOTIFY_CHANGE_SECURITY,
    None,
    None
  )
  for action, file in results:
      if file.endswith(".one"):
          if action in (1, 2, 3):
              full_filename = os.path.join (path_to_watch, file)
              Msg = o.CreateItem(0)
              Msg.To = "emailaddress"
              Msg.Subject = "NOTIFICATION OF UPDATE"
              newbodyvariable = str(full_filename) + " has been " + str(ACTIONS.get (action, "Unknown"))
              Msg.Body = newbodyvariable
              Msg.Send()

1 个答案:

答案 0 :(得分:0)

您是否只需每10分钟检查一次,然后通过电子邮件发送汇总数据?

import time
while 1:
      time.sleep(60 * 10)
      results = win32file.ReadDirectoryChangesW (
        hDir,
        1024,
        True,
        win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
         win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
         win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
         win32con.FILE_NOTIFY_CHANGE_SIZE |
         win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
         win32con.FILE_NOTIFY_CHANGE_SECURITY,
        None,
        None
      )
      all_changes = []
      for action, file in results:
          if file.endswith(".one"):
              if action in (1, 2, 3):
                  full_filename = os.path.join (path_to_watch, file)
                  all_changes.append((full_filename, ACTIONS.get (action, "Unknown")))
      if all_changes:
          Msg = o.CreateItem(0)
          Msg.To = "emailaddress"
          Msg.Subject = "NOTIFICATION OF UPDATE"
          newbodyvariable = "; ".join("{full_filename} has been {action}".format(full_filename, action) for full_filename, action in all_changes)
          Msg.Body = newbodyvariable
          Msg.Send()