Get Inbox associated with mailbox that is not the main mailbox - vba

I'm trying to get the inbox of a specific email address where there is more than one address connected to the same Outlook.
I can only succeed if I check the main mailbox (the first listed in Outlook).
dim outlApp as Object
dim outlNsp as Object
dim outlMapp as Object
dim outlsubMapp as Object
dim Mappar as Object
outlApp = CreateObject("Outlook.Application")
outlNsp = outlApp.GetNamespace("MAPI")
outlMapp = outlNsp.Folders.item(Mail_username)
Mappar = outlMapp.Folders
outlsubMapp = Mappar.item(6)
'6 is olFolderInbox enum value
outlsubMapp = outlNsp.GetDefaultFolder(6)
'6 is olFolderInbox enum value
Inbox = outlsubMapp.Name
If I change Mail_username I still get the first email inbox folder.

This macro lists every store to which you have access and the top level folders which will include their Inboxes. It shows how to access stores and folders that are not defaults.
I am not sure if this is a complete answer but it will get you started. Try the macro then come back with any questions.
Sub ListStoresAndTopLevelFolders()
Dim FldrCrnt As Folder
Dim InxFldrChild As Long
Dim InxStoreCrnt As Long
Dim StoreCrnt As Folder
With Application.Session
For InxStoreCrnt = 1 To .Folders.Count
Set StoreCrnt = .Folders(InxStoreCrnt)
With StoreCrnt
Debug.Print .Name
For InxFldrChild = .Folders.Count To 1 Step -1
Set FldrCrnt = .Folders(InxFldrChild)
With FldrCrnt
Debug.Print " " & .Name
End With
Next
End With
Next
End With
End Sub

You can use the Store.GetDefaultFolder method which returns a Folder object that represents the default folder in the store and that is of the type specified by the FolderType argument. This method is similar to the GetDefaultFolder method of the NameSpace object. The difference is that this method gets the default folder on the delivery store that is associated with the account, whereas NameSpace.GetDefaultFolder returns the default folder on the default store for the current profile.
To get all stores in the profile you need to use the Stores property of the Namespace class:
Sub EnumerateFoldersInStores()
Dim colStores As Outlook.Stores
Dim oStore As Outlook.Store
Dim oRoot As Outlook.Folder
On Error Resume Next
Set colStores = Application.Session.Stores
For Each oStore In colStores
Set oRoot = oStore.GetRootFolder
Debug.Print (oRoot.FolderPath)
EnumerateFolders oRoot
Next
End Sub
Private Sub EnumerateFolders(ByVal oFolder As Outlook.Folder)
Dim folders As Outlook.folders
Dim Folder As Outlook.Folder
Dim foldercount As Integer
On Error Resume Next
Set folders = oFolder.folders
foldercount = folders.Count
'Check if there are any folders below oFolder
If foldercount Then
For Each Folder In folders
Debug.Print (Folder.FolderPath)
EnumerateFolders Folder
Next
End If
End Sub

Related

How to run code on second inbox (shared account)?

I move an email to a specific subfolder of the inbox as soon as it has been tagged with the tag "Invoice".
Private WithEvents objInboxFolder As Outlook.Folder
Private WithEvents objInboxItems As Outlook.Items
'Process inbox mails
Private Sub Application_Startup()
Set objInboxFolder = Outlook.Application.Session.GetDefaultFolder(olFolderInbox)
Set objInboxItems = objInboxFolder.Items
End Sub
'Occurs when changing item
Private Sub objInboxItems_ItemChange(ByVal Item As Object)
Dim objMail As Outlook.MailItem
Dim objTargetFolder As Outlook.Folder
If TypeOf Item Is MailItem Then
Set objMail = Item
'Move mails based on color category
If InStr(objMail.Categories, "Invoice") > 0 Then
Set objTargetFolder = Application.Session.GetDefaultFolder(olFolderInbox).Folders("Invoices").Folders("Uploaded")
objMail.Move objTargetFolder
End If
End If
End Sub
I have two mailboxes/accounts in Outlook. My personal email address as well as Accounting#company.com (used by multiple people).
How do I address the Accounting inbox?
You can use the Store.GetDefaultFolder method which returns a Folder object that represents the default folder in the store and that is of the type specified by the FolderType argument. This method is similar to the GetDefaultFolder method of the NameSpace object. The difference is that this method gets the default folder on the delivery store that is associated with the account, whereas NameSpace.GetDefaultFolder returns the default folder on the default store for the current profile.
So, you can enumerate stores in the Outlook profile and find the required one. For example, the following code shows how to iterate over all stores and folders in Outlook recursively:
Sub EnumerateFoldersInStores()
Dim colStores As Outlook.Stores
Dim oStore As Outlook.Store
Dim oRoot As Outlook.Folder
On Error Resume Next
Set colStores = Application.Session.Stores
For Each oStore In colStores
Set oRoot = oStore.GetRootFolder
Debug.Print (oRoot.FolderPath)
EnumerateFolders oRoot
Next
End Sub
Private Sub EnumerateFolders(ByVal oFolder As Outlook.Folder)
Dim folders As Outlook.folders
Dim Folder As Outlook.Folder
Dim foldercount As Integer
On Error Resume Next
Set folders = oFolder.folders
foldercount = folders.Count
'Check if there are any folders below oFolder
If foldercount Then
For Each Folder In folders
Debug.Print (Folder.FolderPath)
EnumerateFolders Folder
Next
End If
End Sub
You can check out the Store.DisplayName property to find the required store in the profile and then get the required inbox folder of the specific store in Outlook.

Switching between accounts then looping through email

I am attempting to dump all emails in the junk email folder of a NON-Default outlook account into the inbox so that I can then perform additional logic on the email.
However I am unable to figure out how to reference the junk box or even the inbox of the non-default account, my code keeps going through my default account even with an account check in place.
Public Sub New_Mail()
Dim oAccount As Outlook.Account
Dim objSourceFolder As Outlook.MAPIFolder
Dim objDestFolder As Outlook.MAPIFolder
dim lngCount as long
lngcount = 0
For Each oAccount In Application.Session.Accounts ' cycle through accounts till we find the one we want
If oAccount = "desired.account#domain.ca" Then
Set objSourceFolder = objNamespace.GetDefaultFolder(olFolderJunk) ' select junk folder of the account
Set objDestFolder = objNamespace.GetDefaultFolder(olFolderInbox) ' select inbox of the account
For lngCount = objSourceFolder.Items.Count To 1 Step -1 ' Go through all items in inbox, if a mail object, move into inbox
Set objVariant = objSourceFolder.Items.Item(dblCount)
DoEvents
If objVariant.Class = olMail Then
Set objCurrentEmail = objVariant ' the inbox item is an email, so change object type to olMail (email object)
objCurrentEmail.Categories = "red category"
objCurrentEmail.Move objDestFolder ' Move the email to the required folder
End If
Next
End If
Next
End Sub
EDIT:
After Eric's Answer I'd like share my now working code.
Private Sub clearJunk()
Dim objVariant As Variant ' Variant object to handle and inbox item
Dim objCurrentEmail As Outlook.MailItem ' Temporary email object for logic
Dim dblCount As Double ' Double used to count email items in the inbox
Dim objStore As Outlook.Store ' Store Object to cycle through email accounts
Dim objRoot As Outlook.Folder ' Folder object to define Inbox of desired account
Dim folders As Outlook.folders ' FolderS object to holder folders...lol
Dim Folder As Outlook.Folder ' Temporary Folder object
Dim foldercount As Integer ' integer to count folders in account
Dim objInboxFolder As Outlook.MAPIFolder ' MAPI folder object to move emails to or from
Dim objJunkFolder As Outlook.MAPIFolder ' MAPI folder object to move emails to or from
Dim objRandomFolder As Outlook.MAPIFolder ' MAPI folder object to move emails to or from
'--------------------------------------------------------------------
' Cycle through each account in outlook client and find desired account
For Each objStore In Application.Session.Stores
If objStore = "desired.account#domain.ca" Then ' If we find the account
Set objRoot = objStore.GetRootFolder ' Store int objRoot Object
On Error Resume Next
Set folders = objRoot.folders ' Check if it has folders
foldercount = folders.Count
If foldercount Then ' if folders exist
For Each Folder In folders ' Go through each folder AND ....
' Look for Junk Email folder, Inbox Folder, and some random customer folder.
' Store in individual objects for future referencing
If Folder.FolderPath = "\\desired.account#domain.ca\Junk Email" Then
Set objJunkFolder = Folder
End If
If Folder.FolderPath = "\\desired.account#domain.ca\Inbox" Then
Set objInboxFolder = Folder
End If
If Folder.FolderPath = "\\desired.account#domain.ca\Random Custom Folder" Then
Set objRandomFolder = Folder
End If
Next
End If
' Now we have everything identified lets move emails!
For dblCount = objJunkFolder.Items.Count To 1 Step -1
Set objVariant = objJunkFolder.Items.Item(dblCount)
DoEvents
If objVariant.Class = olMail Then
Set objCurrentEmail = objVariant
objCurrentEmail.Categories = "Red Category"
objCurrentEmail.Move objInboxFolder
End If
Next
End If
Next
End Sub
You need to call Store.GetDefaultFolder(olFolderInbox) for the non-default accounts. Get the Store object from the Account.DeliveryStore property - in most cases that will be the correct store unless for example it is a PST account that has messages delivered to another account's store (perhaps even the default account's store).

How to move messages from a specific account?

I have multiple accounts attached to Outlook 2010.
I want to move messages from a specific account, older than X days, to a .pst file for local storage.
I found scripts to move messages from the default inbox, but nothing on specifying an account.
I know you can specify an account when sending email using
Set OutMail.SendUsingAccount = Outlook.Application.Session.Accounts.Item(2)
but I can't find anything for looking into another account.
I've found the stores references for the folders (\Inbox and \Sent) and I know how to specify the days old. I have a script that works, but only in my primary account.
After some more searching and testing I came up with the following solution. This was actually from a 2009 post on stackoverflow here: Original VBA
It uses a public function to build the folder locations and a Subroutine to look for received dates older than 60 days and move those files to the specified locations.
The public function is:
Public Function GetFolder(strFolderPath As String) As MAPIFolder
Dim objNS As NameSpace
Dim colFolders As folders
Dim objFolder As MAPIFolder
Dim arrFolders() As String
Dim i As Long
On Error GoTo TrapError
strFolderPath = Replace(strFolderPath, "/", "\")
arrFolders() = Split(strFolderPath, "\")
Set objNS = GetNamespace("MAPI")
On Error Resume Next
Set objFolder = objNS.folders.Item(arrFolders(0))
If Not objFolder Is Nothing Then
For i = 1 To UBound(arrFolders)
Set colFolders = objFolder.folders
Set objFolder = Nothing
Set objFolder = colFolders.Item(arrFolders(i))
If objFolder Is Nothing Then
Exit For
End If
Next
End If
On Error GoTo TrapError
Set GetFolder = objFolder
Set colFolders = Nothing
Set objNS = Nothing
Exit_Proc:
Exit Function
TrapError:
MsgBox Err.Number & " " & Err.Description
End Function
The subroutine that does the actual work is below.
I added the Pass as Integer to allow the routine to work through two different source and destination folders. If I change the Sub name to Application_Startup it will run whenever outlook is started.
PST Folder Name\Archive-Inbox - PST folder name in Outlook with sub-folder
Email Account Name\Inbox - Account name in Outlook with sub-folder
Sub MoveOldEmail()
Dim oItem As MailItem
Dim objMoveFolder As MAPIFolder
Dim objInboxFolder As MAPIFolder
Dim i As Integer
Dim Pass As Integer
For Pass = 1 To 2
If Pass = 1 Then
Set objMoveFolder = GetFolder("PST Folder Name\Archive-Inbox")
Set objInboxFolder = GetFolder("Email Account Name\Inbox")
ElseIf Pass = 2 Then
Set objMoveFolder = GetFolder("PST Folder Name\Archive-Sent Items")
Set objInboxFolder = GetFolder("Email Account Name\Sent Items")
End If
For i = objInboxFolder.Items.Count - 1 To 0 Step -1
With objInboxFolder.Items(i)
''Error 438 is returned when .receivedtime is not supported
On Error Resume Next
If .ReceivedTime < DateAdd("d", -60, Now) Then
If Err.Number = 0 Then
.Move objMoveFolder
Else
Err.Clear
End If
End If
End With
Next
Next Pass
Set objMoveFolder = Nothing
Set objInboxFolder = Nothing
End Sub
Hope this helps someone else.

How to create a top-level folder in my Outlook using vb.net - VB.NET, Outlook 2013

So as the title says, I am trying to create a top-level folder in my Outlook but I haven't got any success with it. I've read several tutorials and code snippets but non of them seem to be a success.
So now i Have this piece of code which creates a folder under the Inbox folder:
Dim objFolder As Outlook.MAPIFolder
Dim objOutlook As Outlook._Application
objOutlook = New Outlook.Application()
objFolder.Folders.Add("Some folder", Outlook.OlDefaultFolders.olFolderInbox)
The question is, how can I create the same folder but then as a top-level folder instead as a sub-folder of the inbox folder.
I already tried to do it like this:
objFolder.Folders.Add("Some folder") but this didn't work.
Top folders (root nodes in the navigation pane) are store. If you need to add a new store in the profile you can use the AddStoreEx method of the Namesapace class which adds a Personal Folders file (.pst) in the specified format to the current profile. See How to: Add or Remove a Store for more information.
In case if you need to create a top-level folder (at the same level with standard folders like Inbox and etc.) you can get the Parent folder object of the Inbox or any other default folder and add a new folder there. For example:
Dim objFolder As Outlook.MAPIFolder
Dim parentFolder as Outlook.MAPIFolder
Dim objOutlook As Outlook._Application
objOutlook = New Outlook.Application()
myNamespace = objOutlook.GetNamespace("MAPI")
objFolder = myNamespace.GetDefaultFolder(olFolderInbox)
parentFolder = objFolder.Parent
parentFolder.Folders.Add("Some folder", Outlook.OlDefaultFolders.olFolderInbox)
Also you may find the GetRootFolder method of the Store class helpful. It returns a Folder object representing the root-level folder of the Store. You can use the GetRootFolder method to enumerate the subfolders of the root folder of the Store. Unlike NameSpace.Folders which contains all folders for all stores in the current profile, Store.GetRootFolder.Folders allows you to enumerate all folders for a given Store object in the current profile.
Sub EnumerateFoldersInStores()
Dim colStores As Outlook.Stores
Dim oStore As Outlook.Store
Dim oRoot As Outlook.Folder
On Error Resume Next
Set colStores = Application.Session.Stores
For Each oStore In colStores
Set oRoot = oStore.GetRootFolder
Debug.Print (oRoot.FolderPath)
EnumerateFolders oRoot
Next
End Sub
Private Sub EnumerateFolders(ByVal oFolder As Outlook.Folder)
Dim folders As Outlook.folders
Dim Folder As Outlook.Folder
Dim foldercount As Integer
On Error Resume Next
Set folders = oFolder.folders
foldercount = folders.Count
'Check if there are any folders below oFolder
If foldercount Then
For Each Folder In folders
Debug.Print (Folder.FolderPath)
EnumerateFolders Folder
Next
End If
Private Sub CreateNewFolder()
Dim oApp As Outlook.Application = New Outlook.Application
Dim oNS As Outlook.NameSpace = oApp.GetNamespace("MAPI")
Dim InboxFolder As Outlook.MAPIFolder = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
Dim customFolder As Outlook.MAPIFolder
Try
customFolder = InboxFolder.Folders.Add("Vellaichamy", Outlook _
.OlDefaultFolders.olFolderInbox)
InboxFolder.Folders("Authorcode").Display()
Catch ex As Exception
MessageBox.Show("The following error occurred: " & ex.Message)
End Try
End Sub

Moving Emails to Public Folder using Dynamic Paths

In our Corporate environment we have a Mailbox (not the default inbox) with many sub folders. We also have a Public Folder which is an exact mirror of the Mailbox folder structure.
I am trying to detect the path of a selected email and move that email to its mirrored folder in the Public Folders.
I would say 95% of this code is correct but I am left with an Outlook error message "Can't move the items."
The code is supposed to do the following:
1. detects the current folder of the selected email(s)
2. converts the MAPIFolder into a path string
3. shortens the string to remove the root Mailbox directory structure
4. adds the remaining string onto the root directory structure of the public folder
5. converts the resulting path back into a MAPIFolder
6. move the selected email(s) to the mirrored folder in the Public Folders
Sub PublicFolderAutoArchive()
Dim olApp As Object
Dim currentNameSpace As NameSpace
Dim wipFolder As MAPIFolder
Dim objFolder As MAPIFolder
Dim pubFolder As String
Dim wipFolderString As String
Dim Messages As Selection
Dim itm As Object
Dim Msg As MailItem
Dim Proceed As VbMsgBoxResult
Set olApp = Application
Set currentNameSpace = olApp.GetNamespace("MAPI")
Set wipFolder = Application.ActiveExplorer.CurrentFolder
Set Messages = ActiveExplorer.Selection
' Destination root directory'
' Tried with both "\\Public Folders" and "Public Folders" .. neither worked
pubFolder = "\\Public Folders\All Public Folders\InboxMirror"
' wipFolder.FolderPath Could be any folder in our mailbox such as:
' "\\Mailbox - Corporate Account\Inbox\SubFolder1\SubFolder2"
' however, the \\Mailbox - Corporate Account\Inbox\" part is
' static and never changes so the variable below removes the static
' section, then the remainder of the path is added onto the root
' of the public folder path which is an exact mirror of the inbox.
' This is to allow a dynamic Archive system where the destination
'path matches the source path except for the root directory.
wipFolderString = Right(wipFolder.FolderPath, Len(wipFolder.FolderPath) - 35)
' tried with and without the & "\" ... neither worked
Set objFolder = GetFolder(pubFolder & wipFolderString & "\")
If Messages.Count = 0 Then
Exit Sub
End If
For Each itm In Messages
If itm.Class = olMail Then
Proceed = MsgBox("Are you sure you want archive the message to the Public Folder?", _
vbYesNo + vbQuestion, "Confirm Archive")
If Proceed = vbYes Then
Set Msg = itm
Msg.Move objFolder
End If
End If
Next
End Sub
Public Function GetFolder(strFolderPath As String) As MAPIFolder
' strFolderPath needs to be something like
' "Public Folders\All Public Folders\Company\Sales" or
' "Personal Folders\Inbox\My Folder"
Dim objApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Dim colFolders As Outlook.Folders
Dim objFolder As Outlook.MAPIFolder
Dim arrFolders() As String
Dim I As Long
On Error Resume Next
strFolderPath = Replace(strFolderPath, "/", "\")
arrFolders() = Split(strFolderPath, "\")
Set objApp = Application
Set objNS = objApp.GetNamespace("MAPI")
Set objFolder = objNS.Folders.Item(arrFolders(0))
If Not objFolder Is Nothing Then
For I = 1 To UBound(arrFolders)
Set colFolders = objFolder.Folders
Set objFolder = Nothing
Set objFolder = colFolders.Item(arrFolders(I))
If objFolder Is Nothing Then
Exit For
End If
Next
End If
Set GetFolder = objFolder
Set colFolders = Nothing
Set objNS = Nothing
Set objApp = Nothing
End Function
Note: The mailbox above is just an example and is not the actual mailbox name. I used MsgBox to confirm the path string was being joined correctly with all appropriate back slashes and that the Right() function was getting what I needed from the source path.
I'm not sure, but should be something like?
set objApp = New Outlook.Application
instead of
set objApp = Application
From glancing at the code, it appears that your GetFolder() implementation doesn't like the double-backslash you're giving at the start of the path. There's even a comment indicating this at the start of the function. Try removing those two chars from the front of pubFolder.
Alternatively, you could alter GetFolder to permit them. A few lines like this should do the trick.
If Left(strFolderPath, 2) = "\\" Then
strFolderPath = Right(strFolderPath, Len(strFolderPath) - 2)
End If