'How can I automate the code below to run automatically when I receive an email?
How can I automate the code below to run automatically when I receive an email ?
This runs if I manually execute it but doesn't when I receive an email in "Auto-Woodgrain" folder.
Option Explicit
Sub Woodgrain()
Dim ol As Outlook.Application
Dim ns As Outlook.NameSpace
Dim fol As Outlook.Folder
Dim I As Object
Dim mi As Outlook.MailItem
Dim at As Outlook.Attachment
Dim fso As Scripting.FileSystemObject
Dim dir As Scripting.Folder
Dim dirName As String
Set fso = New Scripting.FileSystemObject
Set ol = New Outlook.Application
Set ns = ol.GetNamespace("MAPI")
Set fol = ns.Folders("Auto-Woodgrain").Folders("Inbox")
For Each I In fol.Items
If I.Class = olMail Then
Set mi = I
If mi.Attachments.Count > 0 Then
'Debug.Print mi.SenderName, mi.ReceivedTime, mi.Attachments.Count
dirName = _
"\\emsfile1\Users Shared Folders\mmiller\Woodgrain\" & _
Format(mi.ReceivedTime, "yyy-mm-dd hh-mm-ss ") & _
Left(Replace(mi.Subject, ":", ""), 10)
If fso.FolderExists(dirName) Then
Set dir = fso.GetFolder(dirName)
Else
Set dir = fso.CreateFolder(dirName)
End If
For Each at In mi.Attachments
'Debug.Print vbTab, at.DisplayName, at.Size
at.SaveAsFile dir.Path & "\" & at.FileName
Next at
End If
End If
Next I
End Sub
Solution 1:[1]
You need to handle the NewMailEx event of the Application class. This event fires once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. The EntryIDsCollection string contains the Entry ID that corresponds to that item. Use the Entry ID returned by the string passed to call the NameSpace.GetItemFromID method and process the item.
Also you may consider setting a handle for the ItemAdd event of the Items class. That is if you are intersted in handling new items for a specific folder.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eugene Astafiev |
