如何创建vbs来检查未读电子邮件

时间:2014-01-21 12:28:43

标签: vba vbscript outlook

我一直在寻找如何为Outlook创建可视化基本脚本的方法,大部分建议来自本网站。不幸的是,它们都没有满足我的确切需求。

脚本的原因:

有一个共享邮箱,我的一些同事可以访问,并且有意检查,但有时可能会被忽略。我想创建一个脚本来检查此共享邮箱中的未读电子邮件,并在该文件夹包含10个以上的电子邮件时通过电子邮件发送特定联系人。

到目前为止我尝试过:

Option Explicit

 Private Sub Main()
  Dim olMAPI As Outlook.NameSpace
  Dim Folder As Outlook.MAPIFolder
  Const FOLDER_TO_OPEN = "Mailbox - John Doe"   'Modify as appropriate

  Set olMAPI = GetObject("", "Outlook.Application") _
                          .GetNamespa   ce("MAPI")
  Call PrintFolderNames(olMAPI.Folders(FOLDER_TO_OPEN), "->")
  Set olMAPI = Nothing
End Sub

 Sub PrintFolderNames(tempfolder As Outlook.MAPIFolder, a$)
  Dim i As Integer
  If tempfolder.Folders.Count Then
     Debug.Print a$ & " " & tempfolder.Name & "  ";
     Debug.Print tempfolder.UnReadItemCount
     For i = 1 To tempfolder.Folders.Count
       Call PrintFolderNames(tempfolder.Folders(i), a$ & "->")
     Next i
  Else
     Debug.Print a$ & " " & tempfolder.Name & "  ";
     Debug.Print tempfolder.UnReadItemCount
  End If
 End Sub

我首先尝试创建一个脚本来检查特定文件夹中的未读电子邮件,但这通常会因语法/运行时错误而失败。我试过了:

但是这会出现编译错误,然后是语法错误。

我也尝试过:

Const olFolderInbox = 6

Set objOutlook = CreateObject("Outlook.Application")

Set objNamespace = objOutlook.GetNamespace("MAPI")
objNamespace.Logon "Default Outlook Profile", , False, True    

Set objFolder = objNamespace.GetDefaultFolder(olFolderInbox)

Set colItems = objFolder.Items
Wscript.Echo colItems.Count

objOutlook.Quit

1 个答案:

答案 0 :(得分:1)

您必须安装Outlook才能使用此代码:

Const olFolderInbox = 6
Const olMailItem = 0
dim objOutlook

call checkForUnreadMails


sub checkForUnreadMails()
    dim objFolder, objNamespace

    'get running outlook application or open outlook
    Set objOutlook = GetObject(, "Outlook.Application")
        If objOutlook Is Nothing Then
            Set objOutlook = CreateObject("Outlook.Application")
        End If

    Set objNamespace = objOutlook.GetNamespace("MAPI")  

    'get inbox folder
    Set objFolder = objNamespace.GetDefaultFolder(olFolderInbox)

    'send mail if more than 10 mails are unread
    if objFolder.UnReadItemCount > 10 then
        sendMail "your@mail.address"
    end if

    'send mail if more folder contains more than 10 mails
    'if objFolder.Items.Count > 10 then
    '   sendMail "your@mail.address"
    'end if
end sub

sub sendMail(address)
    dim oItem
    Set oItem = objOutlook.CreateItem(olMailItem)

    With oItem
         .To = address
         .Subject = "Unread mails!"
         .Body = "You have too many unread mails!"
         .send
    End With
end sub