'Best way to change the "From" address on an arriving email in Outlook's VBA script?

My overall goal is to change the "From" sender on an incoming email to something else. Specifically, I get chat logs from Zopim chat and they're all coming from Zopim's "no-reply" email. However, I want these chat logs to be associated with in my CRM and thus I want them associated to people who we chat with.

I've created this VBA script, it runs without errors, however, no change is done to the incoming email. What am I doing wrong?

    Option Explicit

Sub ZopimChatMessageRule(Item As Outlook.MailItem)
    Dim body As String
    Dim sndr As String

    On Error GoTo Finally
    body = Trim(Right(Item.body, Len(Item.body) - (InStrRev(Item.body, "EMAIL") + 5)))
    sndr = Trim(Left(body, InStr(body, vbCrLf) - 1))

    Item.sender.Address = sndr
    Item.sender.Name = sndr
    Item.sender.Update

    Item.Recipients.ResolveAll
    Item.Save

Finally:

End Sub


Solution 1:[1]

Your code is updating the name and address of a one-off address entry that does not exist anywhere. What you need to do is change the Sender and SentOnBehalfOf properties, which are read-only in the Outlook Object Model.

You can use MailItem.PropertyAccessor.SetProperty to update dozen or so PR_SENDER_xyz and PR_SENT_REPRESENTING_xyz MAPI properties - take a look at a message with OutlookSpy (I am its author - click IMessage button). Keep in mind that SetProperty will prevent you from modifying some properties Outlook considers "special".

If using Redemption is an option (I am also its author), you can set the Sender and SentOnBehalfOf properties directly:

set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT
set Msg = Session.GetRDOObjectFromOutlookObject(Item )
strEntryID = Session.AddressBook.CreateOneOffEntryID("Fake User", "SMTP", "[email protected]", false, true)
set addressEntry = Session.AddressBook.GetAddressEntryFromID(strEntryID)
Msg.Sender = addressEntry
Msg.SentOnBehalfOf = addressEntry
Msg.Save

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