Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vba

outlook

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 = '[email protected]' it becomes '[email protected]'.

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 = "[email protected]"  ' Nope , It does not work
   Item.Subject = "New Subject" ' It works

End Sub

Thanks

like image 571
Abdullah Avatar asked Oct 08 '11 13:10

Abdullah


2 Answers

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("[email protected]")
 myItem.Subject = "New Subject"
 myItem.Display

End Sub
like image 144
joeschwa Avatar answered Sep 28 '22 07:09

joeschwa


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 = "[email protected]"
    Else
        newEm = Rec.AddressEntry
   End If

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

   Next

   myItem.Send

End Sub
like image 36
Abdullah Avatar answered Sep 28 '22 06:09

Abdullah