Create Rule to Move Email By Sender Domain - vba

I currently am able to use the macro below to create a Rule that will send all email with the Selected sender address to a designated folder.
This works fine. However I want to create the rule to send all email from that domain (regardless of sender) to the folder.
Here is the code I am currently using.
Dim colRules As Outlook.Rules
Dim oRule As Outlook.Rule
Dim colRuleActions As Outlook.RuleActions
Dim oMoveRuleAction As Outlook.MoveOrCopyRuleAction
Dim oFromCondition As Outlook.ToOrFromRuleCondition
Dim oRuleCondition As Outlook.AddressRuleCondition
Dim oExceptSubject As Outlook.TextRuleCondition
Dim oInbox As Outlook.Folder
Dim oMoveTarget As Outlook.Folder
'Specify target folder for rule move action
Set oInbox = Application.Session.GetDefaultFolder(olFolderInbox)
'Assume that target folder already exists
Set oMoveTarget = Application.Session.Folders("myinbox").Folders("Folders").Folders("Reference").Folders("Vendor Marketing")
'Get Rules from Session.DefaultStore object
Set colRules = Application.Session.DefaultStore.GetRules()
Dim sSender As String
For Each objItem In Application.ActiveExplorer.Selection
If objItem.Class = olMail Then
sSender = objItem.SenderEmailAddress
End If
Next
Dim domain() As String
domain = Split(sSender, "#")
Dim dDomain As String
dDomain = "#" + domain(1)
'Create the rule by adding a Receive Rule to Rules collection
If MsgBox("Do you want to create a rule for " + sSender + "?", vbOKCancel) = vbOK Then
Set oRule = colRules.Create(sSender, olRuleReceive)
'Specify the condition in a ToOrFromRuleCondition object
Set oFromCondition = oRule.Conditions.From
With oFromCondition
.Enabled = True
.Recipients.Add (sSender)
.Recipients.ResolveAll
End With
'Specify the action in a MoveOrCopyRuleAction object
'Action is to move the message to the target folder
Set oMoveRuleAction = oRule.Actions.moveToFolder
With oMoveRuleAction
.Enabled = True
.Folder = oMoveTarget
End With
'Update the server and display progress dialog
colRules.Save
oRule.Execute ShowProgress:=True
End If

Ok, so after much more diggings/trial and error. I found a solution.
The main thing to see is that the type is "AddressRuleCondition" and the property you want to modify is not "Text", but is "Address"
Dim colRules As Outlook.Rules
Dim oRule As Outlook.Rule
Dim colRuleActions As Outlook.RuleActions
Dim oMoveRuleAction As Outlook.MoveOrCopyRuleAction
Dim oFromCondition As Outlook.ToOrFromRuleCondition
Dim oRuleCondition As Outlook.AddressRuleCondition <--------HERE
Dim oExceptSubject As Outlook.TextRuleCondition
Dim oInbox As Outlook.Folder
Dim oMoveTarget As Outlook.Folder
'Specify target folder for rule move action
Set oInbox = Application.Session.GetDefaultFolder(olFolderInbox)
'Assume that target folder already exists
Set oMoveTarget = Application.Session.Folders("myinbox").Folders("Folders").Folders("Reference").Folders("Vendor Marketing")
'Get Rules from Session.DefaultStore object
Set colRules = Application.Session.DefaultStore.GetRules()
Dim sSender As String
For Each objItem In Application.ActiveExplorer.Selection
If objItem.Class = olMail Then
sSender = objItem.SenderEmailAddress
End If
Next
Dim domain() As String
domain = Split(sSender, "#")
Dim dDomain As String
dDomain = "#" + domain(1)
'Create the rule by adding a Receive Rule to Rules collection
If MsgBox("Do you want to create a rule for " + dDomain + "?", vbOKCancel) = vbOK Then
Set oRule = colRules.Create(dDomain, olRuleReceive)
'Specify the condition in a ToOrFromRuleCondition object
'Set oFromCondition = oRule.Conditions.From
'With oFromCondition
'.Enabled = True
'.Recipients.Add (sSender)
'.Recipients.ResolveAll
'End With
Set oRuleCondition = oRule.Conditions.SenderAddress
With oRuleCondition
.Enabled = True
.Address = Array(dDomain) <--------HERE
End With
'Specify the action in a MoveOrCopyRuleAction object
'Action is to move the message to the target folder
Set oMoveRuleAction = oRule.Actions.moveToFolder
With oMoveRuleAction
.Enabled = True
.Folder = oMoveTarget
End With
'Update the server and display progress dialog
colRules.Save
oRule.Execute ShowProgress:=True
End If

Related

Create rule with array (in Outlook)

When I receive e-mail I need check mail body. And I have keywords-more than thousand- If mail has that words, rules should be move to a specific folder. I use this script:
CreateRule()
Dim colRules As Outlook.rules
Dim oRule As Outlook.Rule
Dim colRuleActions As Outlook.RuleActions
Dim oMoveRuleAction As Outlook.MoveOrCopyRuleAction
Dim oFromCondition As Outlook.ToOrFromRuleCondition
Dim oExceptSubject As Outlook.TextRuleCondition
Dim oInbox As Outlook.Folder
Dim oMoveTarget As Outlook.Folder
Set oInbox = Application.Session.GetDefaultFolder(olFolderInbox)
Set oMoveTarget = oInbox.Folders("test").Folders("subTest")
Set colRules = Application.Session.DefaultStore.GetRules()
Set oRule = colRules.Create("ruleTest", olRuleReceive)
Set oMoveRuleAction = oRule.Actions.MoveToFolder
With oMoveRuleAction
.Enabled = True
.Folder = oMoveTarget
End With
Set oExceptSubject = _
oRule.Conditions.BodyOrSubject
With oExceptSubject
.Enabled = True
.Text = Array("my keywords")
End with
colRules.Save
End Sub
But this script dont accept all my keywords, how can I add them in rule...
You need to split the array with commas as the following sample shows:
'Add the subjects to the rule condition
For Each objRuleCondition In objSpecificRule.Conditions
If objRuleCondition.ConditionType = olConditionSubject Then
If objRuleCondition.Enabled = True Then
Set objTextRuleCondition = objRuleCondition
strTextArray = objTextRuleCondition.Text
varSubjects = objDictionary.Keys
varNewTextArray = Split(Join(strTextArray, ",") & "," & Join(varSubjects, ","), ",")
objTextRuleCondition.Text = varNewTextArray
End If
End If
Next
See How to Quickly Add the Subjects of Multiple Emails to the Condition of a Specific Outlook Rule for more information.

Create Outlook email routing rule based on ticket ID using VBA

I tried to create email routing rule with below scenario.
Incoming email will be located at Inbox/Active folder. Subject of the email will contain the ticket ID and content
Once new email coming to Active subfolder, Outlook will get the email subject and create the subfolder with format "ticket ID - content" eg: "123123 - issue with outlook"
Then a rule will be created to route this incoming email with ticket ID to the subfolder that I just created
Below is my code but it did not work. Only subfolder is created as expected. Please help me to review if any idea. Thanks
Option Explicit
Private WithEvents inboxItems As Outlook.Items
Private Sub Application_Startup()
Dim olapp As Outlook.Application
Dim olnamespace As Outlook.NameSpace
Set olapp = Outlook.Application
Set olnamespace = olapp.GetNamespace("MAPI")
Set inboxItems = olnamespace.GetDefaultFolder(olFolderInbox).Folders("Filter").Items
End Sub
Private Sub inboxItems_ItemAdd(ByVal Item As Object)
On Error GoTo ErrorHandler
Dim olapp As Outlook.Application
Dim olnamespace As Outlook.NameSpace
Dim olActivefolder As Folder
Dim ticketnumber As String
Dim rightsubject As String
Dim leftsubject As String
Dim extsubject As String
Dim colRules As Outlook.Rules
Dim oRule As Outlook.Rule
Dim colRuleActions As Outlook.RuleActions
Dim oMoveRuleAction As Outlook.MoveOrCopyRuleAction
Dim oFromCondition As Outlook.ToOrFromRuleCondition
Dim oExceptSubject As Outlook.TextRuleCondition
Dim oInbox As Outlook.Folder
Dim oMoveTarget As Outlook.Folder
Set olapp = Outlook.Application
Set olnamespace = olapp.GetNamespace("MAPI")
Set olActivefolder = olnamespace.GetDefaultFolder(olFolderInbox).Folders("Active")
If TypeName(Item) = "MailItem" Then
Debug.Print "triggered"
ticketnumber = Item.Subject
rightsubject = Right(ticketnumber, 16)
leftsubject = Left(ticketnumber, 60)
olActivefolder.Folders.Add (rightsubject & " - " & leftsubject)
End If
Set oInbox = Application.Session.GetDefaultFolder(olFolderInbox).Folders("Active")
Set oMoveTarget = oInbox.Folders(rightsubject & " - " & leftsubject)
Set colRules = Application.Session.DefaultStore.GetRules()
Set oRule = colRules.Create(rightsubject, olRuleReceive)
Set oFromCondition = oRule.Conditions.Subject
With oFromCondition
.Enabled = True
.Text = rightsubject
End With
Set oMoveRuleAction = oRule.Actions.MoveToFolder
With oMoveRuleAction
.Enabled = True
.Folder = oMoveTarget
End With
colRules.Save
ExitNewItem:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ExitNewItem
End Sub
The subject condition should look like this:
'Dim oFromCondition As Outlook.ToOrFromRuleCondition
'Set oFromCondition = oRule.Conditions.subject
'With oFromCondition
' .Enabled = True
' .Text = rightSubject
'End With
Dim oSubjectCondition As TextRuleCondition
Set oSubjectCondition = oRule.Conditions.subject
With oSubjectCondition
.Enabled = True
.Text = Array(rightSubject)
End With
There is likely no need for rules.
Private Sub inboxItems_ItemAdd_Test()
inboxItems_ItemAdd ActiveInspector.CurrentItem
End Sub
Private Sub inboxItems_ItemAdd(ByVal Item As Object)
' Folder created for first mail
' No folder created for subsequent mail
Dim oInbox As folder
Dim oActivefolder As folder
Dim oMoveTarget As folder
Dim oFolder As folder
Dim ticketNumber As String
Set oInbox = Session.GetDefaultFolder(olFolderInbox)
Set oActivefolder = oInbox.Folders("Active")
If TypeName(Item) = "MailItem" Then
Debug.Print "triggered"
' For testing
ticketNumber = "123123"
For Each oFolder In oActivefolder.Folders
If oFolder.Name = ticketNumber Then
Set oMoveTarget = oActivefolder.Folders(ticketNumber)
Debug.Print " Folder exists: " & oMoveTarget.Name
Exit For
End If
Next
If oMoveTarget Is Nothing Then
Set oMoveTarget = oActivefolder.Folders.Add(ticketNumber)
Debug.Print " Folder added: " & oMoveTarget.Name
End If
Item.Move oMoveTarget
End If
Debug.Print "Done."
End Sub

Issue with Class Module Outlook VBA

I am new to VBA and am trying to insert a class module to save an email that arrives to a sub-folder in the inbox called "My Folder" to a location on a sharedrive. I have the below code and have tried sending emails to test but it is not working and cannot figure out why. Any help would be greatly appreciated!
Private WithEvents InboxItems As Outlook.Items
Sub Application_Startup()
Dim xNameSpace As Outlook.NameSpace
Set xNameSpace = Outlook.Application.Session
Set InboxItems = xNameSpace.GetDefaultFolder(olFolderInbox)
Set InboxItems = olFolder.Folders("My Folder")
End Sub
Private Sub InboxItems_ItemAdd(ByVal objItem As Object)
Dim FSO
Dim xMailItem As Outlook.MailItem
Dim xFilePath As String
Dim xRegEx
Dim xFileName As String
On Error Resume Next
xFilePath = CreateObject("WScript.Shell").SpecialFolders(16)
xFilePath = xFilePath & "File Path on Share Drive will be entered here"
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists(xFilePath) = False Then
FSO.CreateFolder (xFilePath)
End If
Set xRegEx = CreateObject("vbscript.regexp")
xRegEx.Global = True
xRegEx.IgnoreCase = False
xRegEx.Pattern = "\||\/|\<|\>|""|:|\*|\\|\?"
If objItem.Class = olMail Then
Set xMailItem = objItem
xFileName = xRegEx.Replace(xMailItem.Subject, "")
xMailItem.SaveAs xFilePath & "\" & xFileName & ".msg", olMSG
End If
Exit Sub
End Sub
There were a few issues with the code that I saw. I have this working, make sure you add this to the ThisOutlookSession object in the VBA IDE.
Private WithEvents InboxItems As Outlook.Items
Private Sub Application_Startup()
Dim outlookApp As Outlook.Application: Set outlookApp = Outlook.Application
Dim objectNS As Outlook.NameSpace: Set objectNS = outlookApp.GetNamespace("MAPI")
Set InboxItems = objectNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub InboxItems_ItemAdd(ByVal Item As Object)
Dim FolderPath As String: FolderPath = "YOUR PATH HERE"
Dim FileName As String
Static FSO As Object
If FSO Is Nothing Then Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists(FolderPath) = False Then FSO.CreateFolder FolderPath
With CreateObject("vbscript.regexp")
.Global = True
.IgnoreCase = False
.Pattern = "\||\/|\<|\>|""|:|\*|\\|\?"
If Item.Class = olMail Then
FileName = .Replace(Item.Subject, vbNullString)
Item.SaveAs FolderPath & FileName & ".msg", olMSG
End If
End With
End Sub

Send Appointment VBA

So, I've been wrestling with this task for WAY too long now. I am trying to make a button that creates an appointment and sends it to someone. So far, I've been successful in creating the appointment with the variables I want, but I can't figure out how to send it to the right person. Or send it at all for that matter. I'm very new to Outlook applications within VBA, so be gentle with me, but here is my code so far:
Sub appt()
Dim OutApp As Object
Dim OutMail As Object
Dim duedate As String
Dim currentrow As String
Dim currentsheet As String
Dim owner As String
currentsheet = ActiveSheet.Name
currentrow = Range("C10:C" & Rows.Count).Cells.SpecialCells(xlCellTypeBlanks).Row
duedate = Range("C" & currentrow).Offset(0, 1)
owner = Range("C" & currentrow).Offset(0, 2)
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(1)
On Error Resume Next
With OutMail
.Recipients = Range("M3")
.Subject = "Next PDB Task for " & currentsheet
.Importance = True
.Start = "8:00 AM" & duedate
.End = "8:00 AM" & Format(Date + 5)
.ReminderMinutesBeforeStart = 10080
.Body = "Text and Stuff"
.Display
End With
Set OutMail = Nothing
Set OutApp = Nothing
Unload Emy
End Sub
So, this is definitely grabbing the information I want from the sheet it's run in, however it's not going anywhere. Do I need to use something other than .Recipients? Is it possible to forward this (with .Forward maybe?)? Any help would be greatly appreciated!!!
P.S. The email address I want to send the appointment to is in cell M3.
I didn't try the scripts, but it looks like they will do what you want.
Sub ResolveName()
Dim myNamespace As Outlook.NameSpace
Dim myRecipient As Outlook.Recipient
Dim CalendarFolder As Outlook.Folder
Set myNamespace = Application.GetNamespace("MAPI")
Set myRecipient = myNamespace.CreateRecipient("Dan Wilson")
myRecipient.Resolve
If myRecipient.Resolved Then
Call ShowCalendar(myNamespace, myRecipient)
End If
End Sub
Sub ShowCalendar(myNamespace, myRecipient)
Dim CalendarFolder As Outlook.Folder
Set CalendarFolder = _
myNamespace.GetSharedDefaultFolder _
(myRecipient, olFolderCalendar)
CalendarFolder.Display
End Sub
excel vba create appointment in someone elses calendar
Sub MultiCalendars()
Dim objPane As Outlook.NavigationPane
Dim objModule As Outlook.CalendarModule
Dim objGroup As Outlook.NavigationGroup
Dim objNavFolder As Outlook.NavigationFolder
Dim objFolder As Folder
Dim calItem As Object
Dim mtgAttendee As Outlook.Recipient
Dim i As Integer
Set Application.ActiveExplorer.CurrentFolder = Session.GetDefaultFolder(olFolderCalendar)
DoEvents
Set objPane = Application.ActiveExplorer.NavigationPane
Set objModule = objPane.Modules.GetNavigationModule(olModuleCalendar)
With objModule.NavigationGroups
Set objGroup = .GetDefaultNavigationGroup(olMyFoldersGroup)
' To use a different calendar group
' Set objGroup = .Item("Shared Calendars")
End With
For i = 1 To objGroup.NavigationFolders.Count
If (objGroup.NavigationFolders.Item(i).Folder.FullFolderPath = "\\Mailbox - Doe, John T\Calendar") Then
Set objNavFolder = objGroup.NavigationFolders.Item(i)
Set calItem = objNavFolder.Folder.Items.Add(olAppointmentItem)
calItem.MeetingStatus = olMeeting
calItem.Subject = "Test Meeting - Ignore"
calItem.Location = "TBD Location"
calItem.Start = #1/19/2015 1:30:00 PM#
calItem.Duration = 90
Set mtgAttendee = calItem.Recipients.Add("John Doe")
mtgAttendee.Type = olRequired
Set mtgAttendee = calItem.Recipients.Add("Jane Doe")
mtgAttendee.Type = olOptional
Set mtgAttendee = calItem.Recipients.Add("CR 101")
mtgAttendee.Type = olResource
calItem.Save
If (calItem.Recipients.ResolveAll) Then
calItem.Send
Else
calItem.Display
End If
End If
Next
Set objPane = Nothing
Set objModule = Nothing
Set objGroup = Nothing
Set objNavFolder = Nothing
Set objFolder = Nothing
Set calItem = Nothing
Set mtgAttendee = Nothing
End Sub
https://answers.microsoft.com/en-us/office/forum/office_2010-customize/excel-vba-create-an-appointment-in-someone-elses/4c2ec8d1-82f2-4b02-abb7-8c2de2fd7656?auth=1

oulook 2003 get all 'From' and 'To' email addresses

I tried this vba to get all Sender and Recipient email addresses from emails in Outlook 2003 folder
Sub GetALLEmailAddresses()
Dim objFolder As Folder
Set objFolder = Application.ActiveExplorer.Selection
Dim dic As Dictionary
Dim strEmail As String
Dim strEmails As String
Dim objItem As MailItem
For Each objItem In objFolder.Items
strEmail = objItem.SenderEmailAddress
'If Not dic.Exists(strEmail) Then
'strEmails = strEmails + strEmail + ";"
'dic.Add strEmail, ""
'End If
Next
Debug.Print strEmails
End Sub
any idea what I am doing wrong?
This is my working example for To values
Sub ExtractEmail()
Dim OlApp As Outlook.Application
Dim Mailobject As Object
Dim Email As String
Dim NS As NameSpace
Dim Folder As MAPIFolder
Set OlApp = CreateObject("Outlook.Application")
' Setup Namespace
Set NS = ThisOutlookSession.Session
' Display select folder dialog
Set Folder = NS.PickFolder
' Create Text File
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("c:\email addresses.txt", True)
' loop to read email address from mail items.
Dim dic
Set dic = CreateObject("Scripting.Dictionary")
Dim strEmails As String
For Each Mailobject In Folder.Items
Email = Mailobject.To
If InStr(1, Email, "kovalovsky.com", vbTextCompare) Then
If Not dic.Exists(Email) Then
strEmails = strEmails + Email + vbCrLf
dic.Add Email, ""
End If
End If
Next
a.WriteLine (strEmails)
Set OlApp = Nothing
Set Mailobject = Nothing
a.Close
End Sub
My code I use in Outlook:
i use it to copy to clipboard but its one email only it doesnt work for whole inbox\folderofchoice
you might be able to create a loop to open your emails get the info then close the email etc etc...
Sub Get_SenderName()
Dim myItem As Outlook.Inspector
Dim objItem As Object
Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
Set myItem = Application.ActiveInspector
If Not TypeName(myItem) = "Nothing" Then
Set objItem = myItem.CurrentItem
sSender = objItem.SenderName
clipboard.SetText sSender
clipboard.PutInClipboard
Else
ErrMsg = MsgBox("No Email Open To Get Data, Please Open Email To Use This.", vbInformation, "You Did It Wrong.")
End If
End Sub