【问题标题】:Is there an Outlook event that occurs when a user attaches a document to an email?当用户将文档附加到电子邮件时是否会发生 Outlook 事件?
【发布时间】:2014-02-05 23:24:34
【问题描述】:

我正在研究检查电子邮件附件大小的项目,它会在发件人尝试附加大型文档时通知他们。我首先使用http://msdn.microsoft.com/en-us/library/office/aa209975(v=office.11).aspx 中显示的示例代码,它在运行 sub TestAttachAdd() 时效果很好。但是,随着代码的运行,当我手动创建新电子邮件并将文件附加到其中时,不会触发 AttachmentAdd 事件。

我是否错误地使用了私有子“newItem_AttachmentAdd”来执行我正在尝试做的事情?

或者是否有其他 Outlook 事件可用于检测用户何时将文档(使用“附加文件”功能区按钮或通过拖放)附加到新电子邮件?

Public WithEvents newItem As Outlook.MailItem

Private Sub newItem_AttachmentAdd(ByVal newAttachment As Attachment)
    If newAttachment.Type = olByValue Then
        newItem.Save
        If newItem.Size > 500 Then '500 bytes used for testing purposes only 
            MsgBox "Warning: Item size is now " & newItem.Size & " bytes."
        End If
    End If
End Sub

Public Sub TestAttachAdd()
    Dim olApp As New Outlook.Application
    Dim atts As Outlook.Attachments
    Dim newAttachment As Outlook.Attachment

    Set newItem = olApp.CreateItem(olMailItem)  
    newItem.Subject = "Test attachment"
    Set atts = newItem.Attachments
    Set newAttachment = atts.Add("C:\Test.txt", olByValue)
End Sub

-------------- 已更新为 2014 年 1 月 27 日的最新工作版本

Public WithEvents goInspectors As outlook.Inspectors
Public WithEvents newItem As outlook.MailItem

Private Sub Initialize_Handlers()
    Set goInspectors = outlook.Application.Inspectors
End Sub

Private Sub Application_Startup()
    Initialize_Handlers
End Sub

Private Sub goInspectors_NewInspector(ByVal Inspector As Inspector)
    If Inspector.CurrentItem.Class = olMail Then
        Set newItem = Inspector.CurrentItem
    End If
End Sub

Private Sub newItem_AttachmentAdd(ByVal newAttachment As Attachment)
    If newAttachment.Type = olByValue Then
        newItem.Save
        If newItem.Size > 500 Then '500 bytes used for testing purposes only
            MsgBox "Warning: Item size is now " & newItem.Size & " bytes."
        End If
    End If
End Sub

【问题讨论】:

    标签: vba vb.net outlook outlook-addin


    【解决方案1】:

    您需要将事件处理程序附加到正确的 MailItem 对象。

    捕获 Application.Inspectors.NewInspector 事件,然后从 Inspector.CurrentItem 检索新项目。

    【讨论】:

    • Dmitry,感谢您回答了我几乎所有的菜鸟问题!不幸的是,我不确定你在说什么,我认为这超出了我对 VB 的基本理解。你有一个例子我可以查看或指向一个网站吗?再次感谢!
    • 我在windowssecrets.com/forums/showthread.php/… 找到了一个代码 sn-p,它显示了一个正常工作的 AttachmentAdd。但它仍然需要先运行 InitializeHandler 子程序。有没有办法让它自动运行,以便我可以检测到用户何时尝试添加附件?
    • 您的代码在哪里运行?它是独立应用还是 COM 插件?
    • 这是在 VBA 中。我能够在 Application_Startup 设置检查器,它现在可以工作了。谢谢,德米特里!
    • 发现了一个错误。重新发布最新版本。因此,如果我打开一封新电子邮件,开始处理它,然后打开另一封电子邮件,如果我切换回第一封电子邮件并尝试附加文档,则大小检查不起作用。我认为这与我Set newItem 的方式有关。有没有办法将Set 最上面的项目设置为newItem?我尝试使用 ActiveInspector.CurrentItem,但我不知道如何让它保持“轮询”,我无法在 newItem_AttachmentAdd 内进行。有任何想法吗?谢谢。
    猜你喜欢
    • 2020-11-21
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2021-10-28
    • 1970-01-01
    • 2014-06-25
    相关资源
    最近更新 更多