2016-01-01 141 views
-2

我正在寫一個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 = "[email protected]" 
    strSMTPTo = "[email protected]" 
    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 
+1

另外,你的問題是什麼?你不確定如何附加文件?你的代碼的其餘部分是否工作?你有錯誤信息嗎?你有沒有嘗試過一些方法來附加文件? – vacip

+0

我想將文件附加在文件夾內 –

+0

試過了,它不起作用 –

回答

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 
+0

@Yousuf我改變了檢查recentFile變量中值的方法;現在試試看看它是否有效 – vacip

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 

TargetInstance對象的Name屬性包含完整路徑到新文件。將您的郵件發送代碼放入SendNotification函數中,並將filename附加到郵件中。