Outlook-如果在本月之前发送过电子邮件,则发出警告

时间:2019-02-20 13:58:14

标签: vba outlook outlook-vba

有没有一种设置代码的方法,所以当我从模板向某人发送电子邮件(通常是一遍又一遍地与我联系)时,它会自动检查我是否已在上个月。

现在我已经为自己建立了一个警告系统,当我发送电子邮件时会显示一个消息框:

Public Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    On Error Resume Next
    If InStr(Item.Body, "A string in my template email") Then
        If MsgBox("Have you sent this already this month?", vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Message Text Warning") = vbNo Then
            Cancel = True
        End If
    End If
End Sub

缺点是我必须手动检查是否已将其发送到特定接收者。 如果我在上个月内未发送过邮件,是否可以以某种方式发送它并发出通知,如果我在上个月内已发送过该邮件,是否会发出警告?

1 个答案:

答案 0 :(得分:1)

您可以在"Sent Items"框中遍历所有已发送的电子邮件,并使用InStr()DateDiff()函数检查自发送以来的内容和日期。

Public Sub Application_ItemSend(ByVal thisItem As Object, Cancel As Boolean)

    Dim ns As Outlook.NameSpace
    Dim folder As MAPIFolder
    Dim Item As Object

    Set ns = Session.Application.GetNamespace("MAPI")
    ' set folder to Sent Items box
    Set folder = ns.GetDefaultFolder(olFolderInbox).Parent.Folders("Sent Items")

    ' iterate thru emails
    For Each Item In folder.Items
        ' check subject content & date difference
        If InStr(Item.subject, "your string here") And DateDiff("m", Item.SentOn, Now) < 1 Then
            ' added this part
            If MsgBox("You have already sent this email this month, do you want to send again?", vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Message Text Warning") = vbNo Then
                ' cancel the email
                Cancel = True
            End If
            Exit For      
        End If    
    Next

End Sub

此外,这是我之前根据情况选择共享收件箱的方法:

Set olApp = CreateObject("Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
Set firstFolder = olNs.Folders("UAT-COE Support Intake Box") ' name of my shared inbox
Set olFolder = firstFolder.Folders("Inbox")

您可能必须执行相同的操作,但是用共享的收件箱名称更改"UAT-COE Support..."。还需要用"Inbox""Sent Items"来更改"Sent"

olFolder设置为正确的“已发送”框后,您可以将其替换为上述代码For each Item in olFolder.Items中的文件夹