使用VBScript,如何在VBS中访问Microsoft Outlook Inbox文件夹之前更新它?

时间:2014-12-18 14:38:19

标签: email vbscript outlook

以下是我使用检查并处理某些Outlook电子邮件和附件的VBScript(VBS)。脚本通过电子邮件地址和主题查找电子邮件。然后,它将附件保存在文件夹中,并将电子邮件移动到Outlook中的文件夹。 (这些代码大部分来自stackoverflow.com帖子,但我忘记了哪一个。)

我的问题:有时这个脚本必须在用户打开当天的Outlook之前运行;因此,没有任何Outlook文件夹已更新,并且由于用户最后关闭Outlook,脚本无法找到已发送给用户的电子邮件。

我的问题:如何更新Outlook收件箱,然后继续执行脚本的其余部分,确保收件箱(或所有Outlook文件夹都已完全更新)?我不确定VBS是否会等待文件夹更新发生,但如果不这样做,我当然需要它。如果等待适用,我不知道如何更新收件箱或等待更新。

欢迎提供有关如何使脚本更好的其他提示。

我的VBScript:

Const olFolderInbox = 6

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutlook = CreateObject("Outlook.Application")

Set objNamespace = objOutlook.GetNamespace("MAPI")
Set objFolder = objNamespace.GetDefaultFolder(olFolderInbox)

Call SaveAndMoveAttachment("'subject 1'", objFolder)
Call SaveAndMoveAttachment("'subject 2'", objFolder)
Call SaveAndMoveAttachment("'subject 3'", objFolder)

Set objFSO = Nothing
Set objOutlook = Nothing
Set objNamespace = Nothing
WScript.Quit

Sub SaveAndMoveAttachment(sSubject, objFolder)
  Set colItems = objFolder.Items
  Set colFilteredItems = colItems.Restrict("[Subject] = " & sSubject)

  If colFilteredItems.count = 0 then
    Msgbox "An email with subject " & sSubject & " in it was not found in your Outlook Inbox"
    WScript.Quit
  end if

  For Each objMessage In colFilteredItems
    Set colAttachments = objMessage.Attachments 
    intCount = colAttachments.Count

    If intCount <> 0  and objMessage.Sender.Address = "support@somesite.com" Then
      For i = 1 To intCount
        strFileName = "Z:\somepath\" & objMessage.Attachments.Item(i).FileName
        objMessage.Attachments.Item(i).SaveAsFile strFileName
        'move the message to somefolder folder
        Set objFoldersomefolder = objNamespace.GetDefaultFolder(olFolderInbox).Folders("somefolder")

        objMessage.Move objFoldersomefolder
      Next
    End If
  Next

  Set colFilteredItems = Nothing
  Set colAttachments = Nothing
  Set colItems = Nothing
End Sub

2 个答案:

答案 0 :(得分:1)

在上面2行之间添加登录步骤

WSCript.Sleep 2000 objNamespace.Logon objNamespace.SendAndReceive(True)

答案 1 :(得分:0)

在这一行之下:

Set objNamespace = objOutlook.GetNamespace("MAPI")

添加:

WSCript.Sleep 2000
objNamespace.SendAndReceive(True) 

我在这里找到了: http://www.experts-exchange.com/Software/Office_Productivity/Groupware/Outlook/Q_28215854.html