发送带附件的电子邮件通知

时间:2016-01-01 21:10:21

标签: vbscript

我正在编写VBScript,以便在文件到达Test文件夹时发送电子邮件通知。我想将该文件附加到我的电子邮箱中。文件名不是常量。每次文件以不同的名称到达时。

以下是我的代码:

Const PATH = "F:\Test"
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim folder: Set folder = fso.GetFolder(PATH)

If folder.Files.Count <> 0 Then
  strSMTPFrom = "errorfile@test.com"
  strSMTPTo = "test@test.com"
  strSMTPRelay = "127.0.0.1"
  strTextBody = "The attached file arrived in Test folder"
  strSubject = "File arrived in Test folder"
  strAttachment = 

  Set oMessage = CreateObject("CDO.Message")
  oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 
  oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTPRelay
  oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 
  oMessage.Configuration.Fields.Update
  oMessage.Subject = strSubject
  oMessage.From = strSMTPFrom
  oMessage.To = strSMTPTo
  oMessage.TextBody = strTextBody
  oMessage.AddAttachment strAttachment
  oMessage.Send
End If

2 个答案:

答案 0 :(得分:1)

我会说你真正想要的是一个文件系统监视器。像这样:

Sub SendNotification(filename)
  'your mail sending code goes here
End Sub

Function CreateMonitor(path)
  Set wmi = GetObject("winmgmts://./root/cimv2")
  Set fso = CreateObject("Scripting.FileSystemObject")

  path = Split(fso.GetAbsolutePathName(path), ":")
  drv  = path(0) & ":"
  dir  = Replace(path(1), "\", "\\")
  If Right(dir, 2) <> "\\" Then dir = dir & "\\"

  query = "SELECT * FROM __InstanceOperationEvent" & _
          " WITHIN 1" _
          " WHERE Targetinstance ISA 'CIM_DataFile'" & _
          " AND TargetInstance.Drive=""" & drv & """" & _
          " AND TargetInstance.Path=""" & dir & """"
  Set CreateMonitor = wmi.ExecNotificationQuery(query)
End Function

Set monitor = CreateMonitor("F:\Test")
Do
  Set evt = monitor.NextEvent()
  If evt.Path_.Class = "__InstanceCreationEvent" Then
    SendNotification evt.TargetInstance.Name
  End If
Loop

Name对象的TargetInstance属性包含新文件的完整路径。将您的邮件发送到SendNotification功能,并将其filename附加到邮件中。

答案 1 :(得分:0)

要查找文件夹中的最新文件,请使用以下代码:

Const PATH = "F:\Test"
dim fso: set fso = CreateObject("Scripting.FileSystemObject")
dim myFolder: set myFolder = fso.getFolder(PATH)
dim myFile
dim recentFile  

For Each myFile in myFolder.Files
  If (isempty(recentFile)) Then
    Set recentFile = myFile
  ElseIf (myFile.DateLastModified > recentFile.DateLastModified) Then
    Set recentFile = myFile
  End If
Next

然后只使用其路径附加文件。

strAttachment = recentFile.path