在 Outlook 的 VBA 脚本中更改到达电子邮件的 "From" 地址的最佳方法?

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

我的总体目标是将收到的电子邮件中的 "From" 发件人更改为其他内容。具体来说,我从 Zopim 聊天室获取聊天记录,它们都来自 Zopim 的 "no-reply" 电子邮件。但是,我希望这些聊天记录与我的 CRM 相关联,因此我希望它们与我们聊天的人相关联。

我已经创建了这个 VBA 脚本,它运行时没有错误,但是,收到的电子邮件没有任何变化。我做错了什么?

    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

您的代码正在更新一个在任何地方都不存在的一次性地址条目的名称和地址。您需要做的是更改 Sender 和 SentOnBehalfOf 属性,这些属性在 Outlook 对象模型中是只读的。

您可以使用 MailItem.PropertyAccessor.SetProperty 更新十几个 PR_SENDER_xyzPR_SENT_REPRESENTING_xyz MAPI 属性 - 查看带有 OutlookSpy 的消息(我是它的作者 -单击 IMessage 按钮)。请记住,SetProperty 将阻止您修改某些 Outlook 认为“特殊”的属性。

如果使用Redemption是一个选项(我也是它的作者),你可以直接设置SenderSentOnBehalfOf属性:

set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT
set Msg = Session.GetRDOObjectFromOutlookObject(Item )
strEntryID = Session.AddressBook.CreateOneOffEntryID("Fake User", "SMTP", "someuser@fake.domain.com", false, true)
set addressEntry = Session.AddressBook.GetAddressEntryFromID(strEntryID)
Msg.Sender = addressEntry
Msg.SentOnBehalfOf = addressEntry
Msg.Save