开发者

Change "Item.To" value in outlook when sending a message using VBA

I'm trying to change the email address in Send To field in Outlook when the user press send button. for example , if the current Item.To value = 'aaa@example.com' it becomes 'bbb@example.com'.

I can change the subject , but failed with Item.To ( is it security issue ? ) :

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

   If Item.Class <> olMail Then Exit Sub

   Item.To = "bbb@example.com"  ' Nope , It doe开发者_运维技巧s not work
   Item.Subject = "New Subject" ' It works

End Sub

Thanks


The MailItem.To property is used only for display names. You probably want to use the Recipients collection as in this slightly modified example from Outlook's Help on the MailItem.Recipients property:

Sub CreateStatusReportToBoss()

 Dim myItem As Outlook.MailItem
 Dim myRecipient As Outlook.Recipient

 Set myItem = Application.CreateItem(olMailItem)
 Set myRecipient = myItem.Recipients.Add("bbb@example.com")
 myItem.Subject = "New Subject"
 myItem.Display

End Sub


I'm the question owner. I chose @joeschwa answer but also I want to display my code that cancel the current message and create new one ( you can change the recipients , message contents and anything else ) :

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

   If Item.Class <> olMail Then Exit Sub
   Dim newEm As String

   Dim Rec As Recipient
        Dim myItem As Outlook.MailItem
        Dim myRecipient As Outlook.Recipient
        Set myItem = Application.CreateItem(olMailItem)
        myItem.Body = Item.Body
        myItem.HTMLBody = Item.HTMLBody
        myItem.Subject = Item.Subject & " RASEEL PLUGIN "
        Cancel = True


   For Each Rec In Item.Recipients
    If InStr(1, Rec.AddressEntry, "@example.com", vbTextCompare) Then
        newEm = "example@example.net"
    Else
        newEm = Rec.AddressEntry
   End If

    Set myRecipient = myItem.Recipients.Add(newEm)
    myRecipient.Type = Rec.Type

   Next

   myItem.Send

End Sub


It works for me. However, when changing recipient, it is also necessary first to delete the previous recipient. For example,

x = .recipients.count if x = 1 then .recipients(1).delete
.recipients.add "abc@dfg.com"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜