The challenge here is getting the handle of the new item (untitled email) while using the Outlook UI rather than creating a new item via VBA. You need to first set the inspectors collection to a user-defined object, which will eventually contain the parent (new inspector) of our new item (untitled email). That can be done by an application level event such as Startup
.
Then, we can use a NewInspector
event to see if the new inspector contains a new message or not; if so, we set it to a module level MailItem object that we have defined on top.
Now, we are set to use a BeforeAttachment
event to check the extension of the file that is being attached, if the extension is a banned extension, it will prompt a message and will cancel attaching.
You can still improve this by making extension comparison better and more accurate or copying the file with banned extensions to the location you want without making you to do that manually or even opening the folder you need to place the files there using windows explorer.
to place the code: ALT + F11, double click on ThisOutlookSession, paste the code and CTRL + S to save
I hope this helped! :)
Option Explicit
Dim WithEvents myItem As Outlook.MailItem
Private WithEvents myOlInspectors As Outlook.Inspectors
Private Sub Application_Startup()
Set myOlInspectors = Application.Inspectors
End Sub
Private Sub myOlInspectors_NewInspector(ByVal Inspector As Outlook.Inspector)
Dim msg As Outlook.MailItem
If Inspector.CurrentItem.Class = olMail Then
Set msg = Inspector.CurrentItem
If msg.Size = 0 Then
'MsgBox "New message" 'uncomment to test this routine
Set myItem = msg
End If
End If
End Sub
Private Sub myItem_BeforeAttachmentAdd(ByVal myAttachment As Attachment, Cancel As Boolean)
Dim sExtension As String
Dim sBannedExtension As String
Dim arr As Variant
sBannedExtension = "xlsx,frm,docx,jpg,png"
arr = Split(myAttachment.FileName, ".")
sExtension = arr(UBound(arr))
If InStr(UCase(sBannedExtension), UCase(sExtension)) > 0 Then
MsgBox "Sorry, you cannot send a file with a(n)" & sExtension & " extension as an attachment according to the new policy."
Cancel = True
End If
End Sub