How to access emails in shared mailbox? - excel

I have two accounts in Outlook one is my personal and another is shared.
I want to read or unread emails of my shared mail box.
I have code that is working with my personal Inbox.
With my shared email group it is showing
Sub OutlookTesting()
Dim folders As Outlook.folders
Dim Folder As Outlook.MAPIFolder
Dim iRow As Integer
Dim Pst_Folder_Name
Dim MailboxName
Dim UnRow As Integer
Dim RESS As Outlook.Recipient
Dim Flag As Integer
'Mailbox or PST Main Folder Name (As how it is displayed in your Outlook Session)
MailboxName = "Dummi#abc.com" 'Mailbox Folder or PST Folder Name (As how it is displayed in your Outlook Session)
Pst_Folder_Name = "Inbox"
' subfolder name
Dim subFolderName As String
subFolderName = "XYZ"
Set Folder = Outlook.Session.folders(MailboxName).folders(Pst_Folder_Name)
If Folder = "" Then
MsgBox "Invalid Data in Input"
GoTo end_lbl1:
End If
'Read Through each Mail and export the details to Excel for Email Archival
For iRow = 1 To Folder.Items.Count
If (Folder.Items(iRow).UnRead) Then
Flag = 0
Set Res = Folder.Items(iRow).Recipients
For Each RESS In Res
If RESS.Name = "ABCD" Or RESS.Name = "PQRS" Then
Flag = 1
End If
Next
If Flag = 1 Then
Folder.Items(iRow).UnRead = True
Else: Folder.Items(iRow).UnRead = False
End If
End If
Next iRow
MsgBox "Outlook Mails Extracted to Excel"
end_lbl1:
End Sub

Hi you can try with the below code(I have edit your above posted code) and also remove unusual code according to your need.
Sub OutlookTesting()
Dim folders As Outlook.folders
Dim folder As Outlook.MAPIFolder
Dim iRow As Integer
Dim Pst_Folder_Name
Dim MailboxName
Dim UnRow As Integer
Dim RESS As Outlook.Recipient
Dim Flag As Integer
Dim olApp As Outlook.Application
Dim olNS As Outlook.Namespace
Dim olfldr As Outlook.MAPIFolder
Dim foldername As Outlook.MAPIFolder
Dim sharedemail As Outlook.Recipient
Set olApp = New Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
Set sharedemail = olNS.CreateRecipient("youremail#abc.com")
Set olfldr = olNS.GetSharedDefaultFolder(sharedemail, olFolderInbox)
Set folder = olfldr
If folder = "" Then
MsgBox "Invalid Data in Input"
GoTo end_lbl1:
End If
'Rad Through each Mail and export the details to Excel for Email Archival
For iRow = 1 To folder.Items.Count
If (folder.Items(iRow).UnRead) Then
Flag = 0
Set Res = folder.Items(iRow).Recipients
For Each RESS In Res
If RESS.Name = "XYZ" Or RESS.Name = "ABC" Then
Flag = 1
End If
Next
If Flag = 1 Then
folder.Items(iRow).UnRead = True
Else: folder.Items(iRow).UnRead = False
End If
End If
Next iRow
MsgBox "Outlook Mails Extracted to Excel"
end_lbl1:
End Sub

Related

Save Outlook attachment using a cell value as the file name

I'm trying to save the Outlook attachment from a particular sub folder to a local path.
I'm able to save the file as is to the local path.
The requirement is to save the xl attachment using a cell value of ThisWorkbook as the file name.
Sub ManualPunchAttachmentsExtract()
Dim OlFolder As Outlook.MAPIFolder
Dim OlMail As Object
Dim OlApp As Outlook.Application
Dim OlItems As Outlook.Items
Dim Get_namespace As Outlook.Namespace
Dim strFolder As String
Dim i As Integer
ThisWorkbook.Activate
Sheets("MP File Save").Activate
Range("H3").Activate
Set OlApp = GetObject(, "Outlook.Application")
If err.Number = 429 Then
Set OlApp = CreateObject("Outlook.Application")
End If
strFolder = InputBox("Please Enter the Folder Path alongwith ' \ ' at the end", Path)
'Set Get_namespace = OlApp.GetNamespace("MAPI")
Set OlFolder = OlApp.GetNamespace("MAPI").Folders("shaikajaz.k#flex.com").Folders("Archive").Folders("Juarez").Folders("Manual Punch")
Set OlItems = OlFolder.Items
'.Restrict("[Unread]=true")
For Each OlMail In OlItems
If OlMail.UnRead = False Then
Else
ThisWorkbook.Activate
Sheets("MP File Save").Activate
ActiveCell.Value = OlMail.Subject
ActiveCell.Offset(0, 1).Value = OlMail.ReceivedTime
If OlMail.attachments.Count > 0 Then
For i = 1 To OlMail.attachments.Count
OlMail.attachments.Item(i).SaveAsFile strFolder & "\" & OlMail.attachments.Item(i).FileName
OlMail.UnRead = False
ThisWorkbook.Activate
ActiveCell.Offset(1, 0).Select
Next i
Else
End If
End If
Next
MsgBox ("Done")
End Sub
First of all, iterating over all items in an Outlook folder is not realy a good idea. Use the Find/FindNext or Restrict methods of the Items class instead. So, instead of the following code:
For Each OlMail In OlItems
If OlMail.UnRead = False Then
Use this:
Private Sub FindAllUnreadEmails(folder As Outlook.MAPIFolder)
Dim searchCriteria As String = "[UnRead] = true"
Dim counter As Integer = 0
Dim mail As Outlook._MailItem = Nothing
Dim folderItems As Outlook.Items = Nothing
Dim resultItem As Object = Nothing
If (folder.UnReadItemCount > 0) Then
folderItems = folder.Items
resultItem = folderItems.Find(searchCriteria)
While Not IsNothing(resultItem)
If (TypeOf (resultItem) Is Outlook._MailItem) Then
counter += 1
mail = resultItem
Debug.Print("#" + counter.ToString() + _
" - Subject: " + mail.Subject)
End If
resultItem = folderItems.FindNext()
End While
Else
Debug.Print("There is no match in the " + _
folder.Name + " folder.")
End If
End Sub
Note, attached files can have the same file name. So, to uniquelly identify files I'd suggest introducing any IDs in the file name when attachments are saved to the disk.
Finally, to save the attached file with a workbook's content name you need to pass a cell value to the SaveAsFile method:
OlMail.attachments.Item(i).SaveAsFile strFolder & "\" & yourWorksheet.Range("B2").Value

Unable to find 'Type Mismatch Error" in VBA

Its works frist time when i am login to the system but for testing second time if i am going to run this code again it will gives me type mismatch error. can somebody help me on this.
Sub Saveattachment()
Application.DisplayAlerts = False
Dim ATMT As Outlook.Attachment
Dim OMAIL As Outlook.MailItem
Dim FOL As Outlook.Folder
Dim ONS As Outlook.Namespace
Dim OLOOK As Outlook.Application
Dim var As Date
Dim count As Long
count = 0
Dim name As String
Dim temp As Variant
Set OLOOK = New Outlook.Application
Set ONS = Outlook.GetNamespace("MAPI")
Set FOL = ONS.Folders("IM_DMBI").Folders("inbox")
Set OMAIL = OLOOK.CreateItem(olMailItem)
msgbox "Please remove old downloads, If already remove please ingore and press Ok to proceed", vbInformation
For Each OMAIL In FOL.items
For Each ATMAT In OMAIL.Attachments
var = Format(OMAIL.ReceivedTime, "MM/DD/YY")
name = Left(OMAIL.Subject, 3)
If name = "304" And var = Date And Err.Number = 13 Then
count = count + 1
ATMAT.SaveAsFile Sheet1.Cells(1, 1) & Application.PathSeparator & ATMAT.filename
End If
If var < Date Then
msgbox "Totlay:-" & count & " Files downloaded for today", vbInformation
Exit Sub
End If
Next
Next
Application.DisplayAlerts = True
End Sub
Screenshot of the error: https://i.stack.imgur.com/5dKPy.png
This helps you to ignore type mismatch error:
Sub GetAttachment()
Application.DisplayAlerts = False
Dim ATMT As Outlook.Attachment
Dim OMAIL As Outlook.MailItem
Dim FOL As Outlook.Folder
Dim ONS As Outlook.Namespace
Dim OLOOK As Outlook.Application
Dim var As Date
Dim count As Long
count = 0
Dim name As String
Dim temp As Variant
Set OLOOK = New Outlook.Application
Set ONS = Outlook.GetNamespace("MAPI")
Set FOL = ONS.Folders("IM_DMBI").Folders("inbox")
Set OMAIL = OLOOK.CreateItem(olMailItem)
'msgbox "Please remove old downloads, If already remove please ingore and press Ok to proceed", vbInformation
For Each OMAIL In FOL.items
On Error GoTo errorHandler
For Each ATMAT In OMAIL.Attachments
var = Format(OMAIL.ReceivedTime, "MM/DD/YY")
name = Left(OMAIL.Subject, 5)
If name = "304 r" And var = Date Then
count = count + 1
ATMAT.SaveAsFile Sheet1.Cells(1, 1) & Application.PathSeparator & ATMAT.filename
End If
If var < Date Then
'msgbox "Totlay:-" & count & " Files downloaded for today", vbInformation
Exit Sub
End If
Next
TypeMismatch:
Next
errorHandler:
If Err = 13 Then 'Type Mismatch
Resume TypeMismatch
End If
Application.DisplayAlerts = True
End Sub
There can be items other than mailitems in the inbox.
Option Explicit ' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration
' If desperate declare as Variant
Sub Saveattachment()
Application.DisplayAlerts = False
'Dim ATMT As outlook.Attachment
Dim ATMAT As outlook.Attachment
Dim oObjItem As Object 'Any type, there can never be a mismatch
Dim OMAIL As outlook.MailItem
Dim FOL As outlook.folder
Dim ONS As outlook.namespace
Dim OLOOK As outlook.Application
Dim var As Date
Dim count As Long
count = 0
Dim name As String
Dim temp As Variant
Set OLOOK = New outlook.Application
'Set ONS = outlook.GetNamespace("MAPI")
Set ONS = OLOOK.GetNamespace("MAPI")
Set FOL = ONS.folders("IM_DMBI").folders("inbox")
'Set OMAIL = OLOOK.CreateItem(olMailItem)
For Each oObjItem In FOL.Items ' any type of item
'For Each OMAIL In FOL.Items
' One of at least three ways to verify
If TypeName(oObjItem) = "MailItem" Then
' Now that you have a mailitem
Set OMAIL = oObjItem
For Each ATMAT In OMAIL.Attachments
Debug.Print "Attachment found."
Next
Else
Debug.Print "This would have been a type mismatch."
End If
Next
Application.DisplayAlerts = True
End Sub

Loop through all outlook items, find emails with email bodies containing a certain text

We have a project at work and basically it should do the following:
Loop through all Outlook items (main email account and its sub folders)
Loop through all Outlook items (user created Data Files (PST files) and its sub folders)
The two loops above should exclude the Yammer Root, Sync Issues, Contacts, and Calendar folders
Find emails with email bodies that contain a certain text (e.g. XXX-YY-2020777), this is for me the most important code
Print these in the worksheet:
main folder - sub folder
sender
email subject
date received
So I found a post useful here, credits to Keith Whatling:
Sub GetEmail()
Dim OutApp As Outlook.Application
Dim Namespace As Outlook.Namespace
Dim Mfolder As Outlook.MAPIFolder
Dim myMail As Outlook.Items
Dim Folder As Outlook.MAPIFolder
Dim SubFolder As Outlook.MAPIFolder
Dim UserFolder As Outlook.MAPIFolder
Set OutApp = New Outlook.Application
Set Namespace = OutApp.GetNamespace("MAPI")
On Error Resume Next
For Each Folder In Namespace.Folders
For Each SubFolder In Folder.Folders
For Each UserFolder In SubFolder.Folders
Debug.Print Folder.Name, "|", SubFolder.Name, "|", UserFolder.Name
Next UserFolder
Next SubFolder
Next Folder
On Error GoTo 0
End Sub
I can combine these two posts:
https://www.encodedna.com/excel/how-to-parse-outlook-emails-and-show-in-excel-worksheet-using-vba.htm
and
Excel vba: Looping through all subfolders in Outlook email to find an email with certain subject
But I need some guidance so I can start this.
I started with
Sub GetEmailTesting()
Dim outlook_app As Outlook.Application
Dim namespace As Outlook.namespace
Set outlook_app = New Outlook.Application
Set namespace = outlook_app.GetNamespace("MAPI")
Dim main_folder As Outlook.MAPIFolder
Dim sub_folder1 As Outlook.MAPIFolder
Dim sub_folder2 As Outlook.MAPIFolder
Dim sub_folder3 As Outlook.MAPIFolder
On Error Resume Next
For Each main_folder In namespace.Folders
' code goes here
For Each sub_folder1 In main_folder.Folders
' code goes here
For Each sub_folder2 In sub_folder1.Folders
' code goes here
For Each sub_folder3 In sub_folder2.Folders
Dim rowNumber As Integer
rowNumber = 2
For Each obj_item In sub_folder3.Items
If obj_item.Class = olMail Then
Dim obj_mail As Outlook.MailItem
Set obj_mail = obj_item
Cells(rowNumber, 1) = obj_mail.SenderEmailAddress
Cells(rowNumber, 2) = obj_mail.To
Cells(rowNumber, 3) = obj_mail.Subject
Cells(rowNumber, 4) = obj_mail.ReceivedTime
End If
rowNumber = rowNumber + 1
Next
Next sub_folder3
Next sub_folder2
Next sub_folder1
Next main_folder
On Error GoTo 0
End Sub
Do I have to insert this in every FOR EACH loop (main folder, subfolder1, subfolder2, subfolder3, and so on and so forth... ?
For Each obj_item In sub_folder3.Items
If obj_item.Class = olMail Then
Dim obj_mail As Outlook.MailItem
Set obj_mail = obj_item
Cells(rowNumber, 1) = obj_mail.SenderEmailAddress
Cells(rowNumber, 2) = obj_mail.To
Cells(rowNumber, 3) = obj_mail.Subject
Cells(rowNumber, 4) = obj_mail.ReceivedTime
End If
rowNumber = rowNumber + 1
Next

Outlook Selecting a Subfolder in the SharedMailbox using GetSharedDefaultFolder Automation error

The following code is to count the number of emails in a particular SharedMailbox or its subfolder.
I am having trouble selecting a subfolder in SharedMailbox.
I have read a number of resources on GetSharedDefaultFolder including this one.
However, struggling to put it together correctly.
Would be really great if you could help with this.
I am experiencing the following error while running the code.
Run-time error '-2147221233 (80040010f)' Automation error
Sub CountInboxSubjects()
Dim olApp As Outlook.Application
Dim olNs As Outlook.Namespace
Dim olFldr As Outlook.MAPIFolder
Dim MyFolder1 As Outlook.MAPIFolder
Dim MyFolder2 As Outlook.MAPIFolder
Dim MyFolder3 As Outlook.MAPIFolder
Dim olMailItem As Outlook.MailItem
Dim propertyAccessor As Outlook.propertyAccessor
Dim olItem As Object
Dim dic As Dictionary
Dim i As Long
Dim Subject As String
Dim val1 As Variant
Dim val2 As Variant
val1 = ThisWorkbook.Worksheets("Data").Range("I2")
val2 = ThisWorkbook.Worksheets("Data").Range("I3")
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
'Set olFldr = olNs.GetDefaultFolder(olFolderInbox)
Set olShareName = olNs.CreateRecipient("Shared_MailBox")
Set olFldr = olNs.GetSharedDefaultFolder(olShareName, olFolderInbox)
MsgBox (olFldr)
Set MyFolder1 = olFldr.Folders("Sub_Folder")
MsgBox (MyFolder1)
Set MyFolder2 = MyFolder1.Folders("Sub_Sub_Folder")
MsgBox (MyFolder2)
Set MyFolder3 = MyFolder1.Folders("Sub_Sub_Folder2")
MsgBox (MyFolder3)
If ThisWorkbook.Worksheets("EPI_Data").Range("I5") = "Inbox" Then
MyFolder = olFldr
ElseIf ThisWorkbook.Worksheets("EPI_Data").Range("I5") = "Sub_Folder" Then
MyFolder = MyFolder1
ElseIf ThisWorkbook.Worksheets("EPI_Data").Range("I5") = "Sub_Sub_Folder" Then
MyFolder = MyFolder2
ElseIf ThisWorkbook.Worksheets("EPI_Data").Range("I5") = "Sub_Sub_Folder" Then
MyFolder = MyFolder3
End If
Set olItem = MyFolder.Items
'Set myRestrictItems = olItem.Restrict("[ReceivedTime]>'" & Format$("01/01/2019 00:00AM", "General Date") & "' And [ReceivedTime]<'" & Format$("01/02/2019 00:00AM", "General Date") & "'")
Set myRestrictItems = olItem.Restrict("[ReceivedTime]>'" & Format$(val1, "General Date") & "' And [ReceivedTime]<'" & Format$(val2, "General Date") & "'")
For Each olItem In myRestrictItems
If olItem.Class = olMail Then
Set propertyAccessor = olItem.propertyAccessor
Subject = propertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0E1D001E")
If dic.Exists(Subject) Then dic(Subject) = dic(Subject) + 1 Else dic(Subject) = 1
End If
Next olItem
With ActiveSheet
.Columns("A:B").Clear
.Range("A1:B1").Value = Array("Count", "Subject")
For i = 0 To dic.Count - 1
.Cells(i + 2, "A") = dic.Items()(i)
.Cells(i + 2, "B") = dic.Keys()(i)
Next
End With
End Sub
After trouble-shooting, I am aware the following step has issues.
Set MyFolder1 = olFldr.Folders("Sub_Folder")
MsgBox (MyFolder1)
I expect the msgbox will return the subfolder name but it's reporting error.
Run-time error '-2147221233 (80040010f)' Automation error
I couldn't find out why. can anyone please help..
Try working with Recipient email address, if recipient name then Attempt to resolve Recipient against the Address Book...
Option Explicit
Public Sub Example()
Dim olApp As Outlook.Application
Set olApp = CreateObject("Outlook.Application")
Dim olNs As Outlook.Namespace
Set olNs = olApp.GetNamespace("MAPI")
Dim Recip As Outlook.Recipient
Dim Inbox As Outlook.MAPIFolder
Set Recip = olNs.CreateRecipient("0m3r#Email.com")
Recip.Resolve
If Recip.Resolved Then
Set Inbox = olNs.GetSharedDefaultFolder _
(Recip, olFolderInbox)
End If
Inbox.Display
End Sub
Of course, you must resolve a recipient's name or address against the address book before accessing shared folders.
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set olShareName = olNs.CreateRecipient("Shared_MailBox")
olShareName.Resolve
If Recip.Resolved Then
Set olFldr = olNs.GetSharedDefaultFolder(olShareName, olFolderInbox)
...
End If
But the cause of the issue with accessing a subfolder is different...
First of all, try to uncheck Download shared folders checkbox checked on the Advanced tab of your Exchange account properties dialog. See the Detecting if ‘Download Shared Folders’ is Checked in Outlook article for more information.
Second, please take a look at the By default, shared mail folders are downloaded in Cached mode in Outlook 2010 and Outlook 2013 article. What value do you have set for the CacheOthersMail key on the PC?
See Accessing subfolders within shared mailbox for more information.

Send email from draft folder

with the below VBA coding, I am able to send all the emails from outlook draft folder but the only problem is that I have to provide the parent folder name. Can we get this details through coding as this macro will be used by other user who is not familiar with VBA.
Dim lDraftItem As Long
Dim myOutlook As Outlook.Application
Dim myNameSpace As Outlook.NameSpace
Dim myFolders As Outlook.Folders
Dim myDraftsFolder As Outlook.MAPIFolder
Set myOutlook = Outlook.Application
Set myNameSpace = myOutlook.GetNamespace("MAPI")
Set myFolders = myNameSpace.Folders
Set myDraftsFolder = myFolders("Gaus_Shaikh2#syntelinc.com").Folders("Drafts")
For lDraftItem = myDraftsFolder.Items.Count To 1 Step -1
If Len(Trim(myDraftsFolder.Items.Item(lDraftItem).To)) > 0 Then
myDraftsFolder.Items.Item(lDraftItem).Send
End If
Next lDraftItem
This should work...
Set myDraftsFolder = myNamespace.GetDefaultFolder(olFolderDrafts)
* Edit *
The code below is probably a better function to use; it has error checking incorporated so any e-mails with invalid fields in the 'To' section shouldn't abort the function
Sub TestSendDrafts()
Call SendDraftMail
End Sub
Function SendDraftMail() As Boolean
On Error GoTo ExitFunction
Dim ThisNameSpace As Outlook.NameSpace: Set ThisNameSpace = Application.GetNamespace("MAPI")
Dim DraftFolder As Outlook.MAPIFolder: Set DraftFolder = ThisNameSpace.GetDefaultFolder(olFolderDrafts)
Dim Var As Variant, i As Long, Difference As Long, SentItems As Long
For i = DraftFolder.Items.Count To 1 Step -1
Set Var = DraftFolder.Items.Item(i)
DoEvents
If Var.Class = olMail Then
If Len(Trim(Var.To)) > 0 Then
On Error Resume Next
Var.Send
If Err.Number = 0 Then SentItems = SentItems + 1
On Error GoTo ExitFunction
End If
End If
Next i
Debug.Print "Sent " & SentItems & " message(s) from 'Draft E-mail'."
SendDraftMail = True
ExitFunction:
End Function
Replace this line:
Set myDraftsFolder = myFolders("Gaus_Shaikh2#syntelinc.com").Folders("Drafts")
With these three lines:
Dim sUser As String
sUser = myFolders.Item(2).Name
Set myDraftsFolder = myFolders(sUser).Folders("Drafts")
The 2nd folder name will be the user account name (e-mail address), which you can store as a string and pass into myFolders() to qualify their specific account.

Resources