Event code to programmatically forward messages in Outlook


On my blog I posted some code to programmatically forward messages to another email address. Here is the code in a wider format. It sits in the ThisOutlookSession module to check incoming messages for a particular subject. If found, it creates a new mail item (via the Forward Method) and sends that message to another email. Then it takes the original message, marks it as unread and quietly moves it to another folder. All without any user intervention required.

Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
Dim objNS As Outlook.NameSpace
Dim objNS As Outlook.NameSpace
Set objNS = GetNamespace("MAPI")
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub

Private Sub Items_ItemAdd(ByVal item As Object)

If item.Class = olMail Then
    If Left$(item.Subject, 16) = "String to search" Then
        Dim Msg As Outlook.MailItem
        Dim NewForward As Outlook.MailItem
        Dim MyFolder As Outlook.MAPIFolder
        Dim olApp As Outlook.Application
        Dim olNS As Outlook.NameSpace

    Set Msg = item
    Set NewForward = Msg.Forward
    Set olApp = Outlook.Application
    Set olNS = olApp.GetNamespace("MAPI")
    Set MyFolder = olNS.GetDefaultFolder(olFolderInbox).Folders("Archive")

        With NewForward
            .Subject = Right(Msg.Subject, Len(Msg.Subject) - InStrRev(Msg.Subject, " "))
            .To = "myemail@mobiledevice.com"
            .HTMLBody = ""
            .Send
        End With

    With Msg
       .UnRead = False
       .FlagStatus = olNoFlag
       .Move MyFolder
    End With
    End If
End If

ExitProc:
Set NewForward = Nothing
Set Msg = Nothing
Set olApp = Nothing
Set olNS = Nothing
Set MyFolder = Nothing
End Sub

Remember the code makes certain assumptions which you should verify before testing the code. For example, the emails are being moved to a folder named "Archive" which is one level below the default Inbox. You can either create this folder, or change the code to point to another folder you want to use for this purpose. Also you should change the email address to match the one you want to use.

Check out the blog post here.

LAST UPDATED: April 27, 2008