简体   繁体   中英

How to auto forward an email from a specific sender and with a specific subject?

I am trying to auto forward an email from a specific sender and with a specific subject to a list of new recipients.

When I create a Run a Script Rule, my script is not shown.

  1. Add my script via VBA Editor
  2. Rules > Manage Rules & Alerts > Run a script
  3. Select Run a script action -> Can not Select my script (script not show)
Option Explicit
 
Public WithEvents objInbox As Outlook.Folder
Public WithEvents objInboxItems As Outlook.Items
 
Private Sub Application_Startup()
    Set objInbox = Outlook.Application.Session.GetDefaultFolder(olFolderInbox)
    Set objInboxItems = objInbox.Items
End Sub
 
Private Sub objInboxItems_ItemAdd(ByVal Item As Object)
    Dim objMail As Outlook.MailItem
    Dim objForward As Outlook.MailItem
 
    Dim xStr1 As String
    Dim xStr2 As String
 
    If TypeOf Item Is MailItem Then
        Set objMail = Item
 
        If (objMail.SenderEmailAddress = "T@com") And (objMail.Subject = "ZZZZZ") Then
            Set objForward = objMail.Forward
            GoTo commonOutput
        End If
 
    End If
    Exit Sub
 
commonOutput:
    With objForward
        .HTMLBody = xStr1 & xStr2 & Item.HTMLBody
        .Display
    End With
 
Release:
    Set myFwd = Nothing
 
End Sub

VBA script which can be assigned to a rule should have the following signature:

Public Sub Test(item as object)
  ' your code 
End Sub

Your existing code does almost the same without rules. It handles the ItemAdd event for the Inbox folder, so you just need to replace the Display method call with Send :

Private Sub objInboxItems_ItemAdd(ByVal Item As Object)
    Dim objMail As Outlook.MailItem
    Dim objForward As Outlook.MailItem

    Dim xStr1 As String
    Dim xStr2 As String

    If TypeOf Item Is MailItem Then
        Set objMail = Item

        If (objMail.SenderEmailAddress = "T@com") And (objMail.Subject = "ZZZZZ") Then
            Set objForward = objMail.Forward
            GoTo commonOutput
        End If

    End If
    Exit Sub

   commonOutput:
    With objForward
        .HTMLBody = xStr1 & xStr2 & Item.HTMLBody
        .Send
    End With

Release:
    Set myFwd = Nothing

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM