使用VBA发送消息时,在Outlook中更改“Item.To”值

时间:2011-10-08 13:16:05

标签: vba outlook outlook-vba

当用户按下发送按钮时,我正在尝试更改Outlook中“发送至”字段中的电子邮件地址。例如,如果当前Item.To值= 'aaa@example.com',则它变为'bbb@example.com'

我可以更改主题,但是使用Item.To失败了(这是安全问题吗?):

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 does not work
   Item.Subject = "New Subject" ' It works

End Sub

由于

3 个答案:

答案 0 :(得分:6)

MailItem.To属性仅用于显示名称。您可能希望使用Recipients集合,就像在MailItem.Recipients属性的Outlook帮助中略微修改的示例一样:

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

答案 1 :(得分:5)

我是问题所有者。我选择了@joeschwa的答案,但我也希望显示取消当前消息并创建新消息的代码(您可以更改收件人,消息内容和其他任何内容):

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

答案 2 :(得分:0)

它对我有用。但是,在更改收件人时,还必须先删除以前的收件人。例如,

x = .recipients.count 如果x = 1,则.recipients(1).delete
.recipients.add“abc@dfg.com”