'How do you Auto Forward email based 'To' field in outlook?
I tried to write the code as below
- Case 1: If the mail is sent TO [email protected] -> AutoForward To [email protected]
- Case 2: If the mail is sent TO [email protected] [email protected] [email protected] -> AutoForward To [email protected] [email protected]
Could you please help me how to code in Case 2: If the mail is sent TO [email protected] [email protected] [email protected] -> AutoForward To [email protected] [email protected]
Sub AutoForwardAllSentItems(Item As Outlook.MailItem)
Dim myFwd As Outlook.MailItem
Set myFwd = Item.Forward
Dim xStr1 As String
Dim xStr2 As String
Dim Recipient As String
Dim recips As Outlook.Recipients
Dim recip As Outlook.Recipient
Dim pa As Outlook.PropertyAccessor
Const PR_SMTP_ADDRESS As String = _
"http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
Set recips = mail.Recipients
For Each recip In recips
'Case 1: If the mail is sent TO [email protected]'
If recip = "[email protected]" Then
Set ToMember = myFwd.Recipients.Add ("[email protected]")
Set CcMember = myFwd.Recipients.Add ("[email protected]")
CcMember.Type = 2
'Case 2: If the mail is sent TO [email protected] [email protected] [email protected]'
ElseIf recip = "[email protected]" "[email protected]" "[email protected]" Then
Recipient = "@f.com"
Recipient = "[email protected]"
Recipient = "[email protected]"
xStr1 = "<p>B1</p>"
xStr2 = "<p>B2</p>"
Else
MsgBox "None of the conditions was true, abort."
Exit Sub
End If
Next
myFwd.Recipients.Add Recipient
myFwd.HTMLBody = xStr1 & xStr2 & Item.HTMLBody
myFwd.Send
Set myFwd = Nothing
End Sub
Solution 1:[1]
Put the most restrictive condition first.
Option Explicit
Sub AutoForwardAllSentItems(Item As mailitem)
Dim myFwd As mailitem
Set myFwd = Item.Forward
Dim xStr1 As String
Dim xStr2 As String
' If the mail is sent TO [email protected] [email protected] [email protected] -> AutoForward To [email protected] [email protected]
If InStr(LCase(Item.To), LCase("[email protected]")) Then
If InStr(LCase(Item.To), LCase("[email protected]")) Then
If InStr(LCase(Item.To), LCase("[email protected]")) Then
myFwd.Recipients.Add ("[email protected]")
myFwd.Recipients.Add ("[email protected]")
xStr1 = "<p>B1</p>"
xStr2 = "<p>B2</p>"
GoTo commonOutput
End If
End If
End If
' If the mail is sent TO [email protected] -> AutoForward To [email protected]
If InStr(LCase(Item.To), LCase("[email protected]")) Then
myFwd.Recipients.Add ("[email protected]")
xStr1 = "<p>A1</p>"
xStr2 = "<p>A2</p>"
GoTo commonOutput
End If
MsgBox "None of the conditions was true, abort."
Exit Sub
commonOutput:
With myFwd
.HtmlBody = xStr1 & xStr2 & Item.HtmlBody
.Display
'.Send
End With
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | niton |
