VBS在早于x分钟的Outlook会话中检查未读邮件

时间:2017-02-03 13:23:34

标签: email vbscript outlook alert

我有一个脚本可以通过任务计划程序运行,检查未读电子邮件并发送电子邮件警报,如下所示。为了进一步增强这一点,我需要能够检查未读电子邮件,并且只有在超过'x'分钟时才发送电子邮件。

有关如何最好地完成此任务的任何想法?

由于

请参阅下面的更新代码,并在回答中包含建议的代码 - 但这会导致语法错误

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 "email@emailaddress.com"
end if

end sub

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

With oItem
     .To = address
     .Subject = "There are unread emails"
     .Body = "Please investigate the mailbox."
     .send
End With
end sub

以下编辑版本:

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)

'look at unread emails
Set UnreadItems = objFolder.Items

'send mail if mails are unread and older than 15 mins
For i = UnreadItems.Count To 1 Step -1
 If TypeName(UnreadItems.Item(i)) = "MailItem" Then
  If DateDiff("n",now, UnreadItems.Item(i).ReceivedTime) > 15 Then
    sendMail "mail@address.com"
    end if
end if
Next

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

    With oItem
     .To = address
     .Subject = "There are unread emails"
     .Body = "Please investigate the mailbox."
     .send
End With
end sub

2 个答案:

答案 0 :(得分:0)

这应该有效:

Set UnreadItems = objFolder.Items
For i = UnreadItems.Count To 1 Step -1
 If TypeName(UnreadItems.Item(i)) = "MailItem" Then
  If DateDiff("n",now, UnreadItems.Item(i).ReceivedTime) > 15 Then 
   //Do something
  End If
 End If
Next

答案 1 :(得分:0)

不要使用任务计划程序中的Outlook对象模型 - 它作为服务运行,并且不能从服务中使用Office应用程序(包括Outlook)。你的代码迟早会破裂。