get email address from outlook to excel - excel

found a code below and im trying to get the email address in my outlook inbox into excel but errors in line set objfolder
Sub getemail()
Dim objFolder As MAPIFolder
Dim strEmail As String
Dim objItem As Object
Dim counter As Integer
counter = 2
Set objFolder = Application.GetNamespace("Mapi").GetDefaultFolder(olFolderInbox)
For Each objItem In objFolder.Items
If objItem.Class = olMail And objItem.ReceivedTime >= DateAdd("yyyy", -1, Now) Then
strEmail = objItem.SenderEmailAddress
Cells(counter, 1).Value = strEmail
counter = counter + 1
End If
Next
End Sub

I am not sure if it got to do with late binding/early binding issue. But you can try to change the "olFolderInbox" to 6.
If you want to use the early binding, make sure your Microsoft Outlook XX.X object library is enabled in your reference.
I typically will use late binding, it will be a lot simpler and you don't have to deal with the reference library version issue. When sharing the sub routine with another colleague or friend with different Excel version
Sub Get_Name()
Dim OLApp As Object
Dim oNameSpace As Object
Dim oFolder As Object
Dim oMail As Object
Set OLApp = CreateObject("Outlook.Application")
Set oNameSpace = OLApp.GetNameSpace("MAPI")
Set oFolder = oNameSpace.GetDefaultFolder(6) 'olFolderInbox: 6, Inbox folder
For Each oMail In oFolder.items
On Error Resume Next
Debug.Print oMail.SenderEmailAddress
'Do your stuff here....
On Error GoTo 0
Next oMail
End Sub

Firstly, never loop through all items in a folder - folders can contain thousands of messages, use Items.Find/FindNext or Items.Restrict.
Secondly, Inbox folder can contain items other than MailItem, such as ReportItem or MeetingItem, which do not expose the SenderEmailAddress property. Check the Class property (exposed by all OOM object) that you indeed have a MailItem object.
Finally, Application intrinsic variable points to the Excel.Application object in Excel VBA. You need to explicitly create an instance of the Outlook.Application object if unless you are running your code in Outlook VBA.
set OlApp = CreateObject("Outlook.Application")
Set objFolder = OlApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
set restrictedItems = objFolder.Items.Restrict("[ReceivedTime] >= '02-07-2023' ")
For Each objItem In restrictedItems
If objItem.Class = olMail Then
strEmail = objItem.SenderEmailAddress
Cells(counter, 1).Value = strEmail
counter = counter + 1
End If
Next

by #Dmitry
make sure to add outlook as project preference
Sub getemail()
Dim OLApp As Object
Dim objFolder As Object
Dim objItem As Object
Dim restrictedItems As Object
Dim olFolderInbox As Object
Dim strEmail As String
Dim counter As Integer
counter = 2
Set OLApp = CreateObject("Outlook.Application")
Set objFolder = OLApp.GetNamespace("MAPI").GetDefaultFolder(6)
Set restrictedItems = objFolder.Items.Restrict("[ReceivedTime] >= '02-07-2023' ")
For Each objItem In restrictedItems
If objItem.Class = 43 Then
strEmail = objItem.SenderEmailAddress
Cells(counter, 1).Value = strEmail
counter = counter + 1
End If
MsgBox "Email address copied"
Next
End Sub

Related

I want to read SenderAddress from office 365 Outlook mail using VBA in excel?

I have tried everything to read a mail from office 365 outlook but I am not able to read it. Every time Sender address is coming empty.
Error That I am getting is :
Run-time error: ‘287’
Application-defined or object-defined error.
Please find the code that I am using.
Option Explicit
Sub Mail()
Dim xNameSpace As Outlook.Namespace
Dim xFolder As Outlook.Folder
Dim xOutlookApp As Outlook.Application
Set xOutlookApp = New Outlook.Application
Set xNameSpace = xOutlookApp.Session
Set xFolder = xNameSpace.GetDefaultFolder(olFolderInbox)
Set xFolder = xFolder.Folders("Retail")
' Set Outlook application object.
Dim objOutlook As Object
Set objOutlook = CreateObject("Outlook.Application")
Dim objNSpace As Object ' Create and Set a NameSpace OBJECT.
' The GetNameSpace() method will represent a specified Namespace.
Set objNSpace = objOutlook.GetNamespace("MAPI")
Dim myFolder As Object ' Create a folder object.
Set myFolder = objNSpace.GetDefaultFolder(olFolderInbox)
Dim objItem As Object
Dim iRows, iCols As Integer
iRows = 2
' Loop through each item in the folder.
For Each objItem In xFolder.Items
If objItem.Class = olMail Then
Dim GetSenderAddress As String
Dim objMail As Outlook.MailItem
Set objMail = objItem
Dim mailType As String
mailType = objMail.SenderEmailType
If mailType = "EX" Then
' GetSenderAddress = GetExchangeSenderAddressNew(objMail)
FindAddress (objMail.SenderEmailAddress)
Else
GetSenderAddress = objMail.SenderEmailAddress
End If
Cells(iRows, 1) = objMail.SenderEmailAddress
Cells(iRows, 2) = objMail.To
Cells(iRows, 3) = objMail.Subject
Cells(iRows, 4) = objMail.ReceivedTime
End If
iRows = iRows + 1
Next
Set objMail = Nothing
' Release.
Set objOutlook = Nothing
Set objNSpace = Nothing
Set myFolder = Nothing
End Sub
Private Function GetExchangeSenderAddress(objMsg As MailItem) As String
Dim oSession As Object
Set oSession = CreateObject("MAPI.Session")
oSession.Logon "", "", False, False
Dim sEntryID As String
Dim sStoreID As String
Dim oCdoMsg As Object
Dim sAddress As String
Const g_PR_SMTP_ADDRESS_W = &H39FE001F
sEntryID = objMsg.EntryID
sStoreID = objMsg.Parent.StoreID
Set oCdoMsg = oSession.GetMessage(sEntryID, sStoreID)
sAddress = oCdoMsg.Sender.Fields(g_PR_SMTP_ADDRESS_W).Value
Set oCdoMsg = Nothing
oSession.Logoff
Set oSession = Nothing
GetExchangeSenderAddress = sAddress
End Function
Another Code is:
Sub Mail()
Dim jsObj As New ScriptControl
jsObj.Language = "JScript"
With jsObj
.AddCode "outlookApp = new ActiveXObject('Outlook.Application'); nameSpace = outlookApp.getNameSpace('MAPI'); nameSpace.logon('','',false,false); mailFolder = nameSpace.getDefaultFolder(6); var Inbox = mailFolder.Folders; var box = Inbox.Item('Retail').Items; "
End With
End Sub
Please let me know if i can read sender address of a mail in office 365 outlook.
First of all, the following lines of code iterates over all items in the folder:
' Loop through each item in the folder.
For Each objItem In xFolder.Items
If objItem.Class = olMail Then
Where you don't check whether it is received or composed item. Composed emails may not have the Sender-related properties set yet, so you can use the CurrentUser property which returns the display name of the currently logged-on user as a Recipient object.
Note, in case of Exchange accounts configured you may use the AddressEntry.GetExchangeUser property which returns an ExchangeUser object that represents the AddressEntry if the AddressEntry belongs to an Exchange AddressList object such as the Global Address List (GAL) and corresponds to an Exchange user.
The ExchangeUser.PrimarySmtpAddress property returns a string representing the primary Simple Mail Transfer Protocol (SMTP) address for the ExchangeUser.

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.

Import Outlook User-Defined Field to Excel with VBA

I would like to import mail data from Outlook.
I have no problem to import classic fields such as: From, Subject ... etc. I cannot find how to import my "User-defined field".
The User-defined field is named "DemandQTY" and contains only numbers.
I get my data from a shared mailbox.
Sub GetFromOutlook()
Dim OutApp As Outlook.Application
Dim OutNS As Namespace
Dim Folder As MAPIFolder
Dim OutMail As Variant
Dim i As Integer
Dim objOwner As Outlook.Recipient
Dim FileName As String
Dim MI As Outlook.MailItem
Dim Item As Object
Dim Atmt As Attachment
Set OutNS = GetNamespace("MAPI")
Set OutApp = New Outlook.Application
Set objOwner = OutNS.CreateRecipient("emailadress")
objOwner.Resolve
If objOwner.Resolved Then
Set Folder = OutNS.GetSharedDefaultFolder(objOwner, olFolderInbox)
i=2
For Each OutMail In Folder.Items
Sheets(2).Cells(i, 1) = OutMail.EntryID
' (etc....)
Sheets(2).Cells(i, 32) = OutMail.ReminderTime
i = i + 1
Next OutMail
MsgBox "Importation Terminée"
Sheets(2).Select
Sheets(2).Cells(1, 1).Select
Set OutApp = Nothing
Set OutNS = Nothing
Set Folder = Nothing
End If
End Sub
I tried different methods found on internet, but nothing worked.
We can do this by first testing if the property exists. If it doesn't and you try to work with it, it will throw an error. Afterwards we can access the value if the property is found.
For Each OutMail In Folder.Items
Sheets(2).Cells(i, 1) = OutMail.EntryID
(etc....)
Sheets(2).Cells(i, 32) = OutMail.ReminderTime
If Not(OutMail.UserProperties.Find("DemandQTY", True) Is Nothing) Then
Sheets(2).Cells(i, 33) = OutMail.UserProperties("DemandQTY").Value
End If
i = i + 1
Next OutMail

How to retrieve SenderEmailAddress from each mail item in an Outlook folder?

I am trying to pull the sender's email address from every email in an inbox folder
I am not having any problems until I reach my For command for each email in the folder.
If I use the code as it is now I run into an error because olSender is not Dim As Variant, but if I change it to Dim As Variant I cannot Dim it as an Outlook.MailItem to retrieve the senderEmailAddress.
I'm assuming a nested For loop is the solution. Outlook 2013 is the version.
Sub ExportToExcel()
'EXCEL
'Opening Excel workbook
Dim oXLApp As Object, oXLwb As Object, oXLws As Object
Dim lRow As Long
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
oXLApp.Visible = True
Set oXLwb = oXLApp.Workbooks.Open("C:\Users\******\Documents\******.xlsm")
Set oXLws = oXLwb.Sheets("Sheet1")
oXLws.Range("A" & 1).Select
'OUTLOOK
'Opening Outlook folder
Dim olNS As Outlook.NameSpace
Dim objOwner As Outlook.Recipient
Set olNS = Application.GetNamespace("MAPI")
Set objOwner = olNS.CreateRecipient("*********#email.com")
objOwner.Resolve
If objOwner.Resolved Then
Set BouncedEmailsFolder = olNS.GetSharedDefaultFolder(objOwner, olFolderInbox).Folders("Bounced Emails")
End If
Dim olItms As Outlook.Items
Dim olMail As Variant
Dim i As Long
Dim olSender As Outlook.MailItem
Set olItms = BouncedEmailsFolder.Items
olItms.Sort ("Subject")
i = 1
For Each olSender In olItms
oXLws.Select
oXLws.Cells(i, 1).Select
oXLws.Cells(i, 1).Value = olSender.SenderEmailAddress
i = i + 1
Next olSender
Set BouncedEmailsFolder = Nothing
Set olNS = Nothing
End Sub
Your code works for me when set to my default inbox.
olNS.GetDefaultFolder(olFolderInbox)
I wonder if you're not coming across non-mail items in your bounced emails? You may want to try the code below, which will retrieve mail items only (instead of also trying to extract the sender for meeting requests, task assignments, etc):
For Each olSender In olItms
If TypeOf olSender Is MailItem Then
oXLws.Select
oXLws.Cells(i, 1).Select
oXLws.Cells(i, 1).Value = olSender.SenderEmailAddress
i = i + 1
End If
Next olSender

Excel VBA Code to retrieve e-mails from outlook

I am to write a VBA code that would retrive emails from Outlook based on certain conditions. The problem I have is that I have to denote a certain folder in my code (in the example below the folder denoted is "PRE Costumer". I would like to retrive all emails from my 'inbox' or in better case from all outlook folders. The problem is that my inbox consists of many subfolders (because of rules0. My problem is that I may not know all the subfolders names (as many useres are going to use the macro and even someone can have the e mails in Personal Folders).
Could you please advise is there a way to overcome this problem?
Please let me know if this question is vague (as I am newcomer)
Please find the line that I have probelm with marked with a comment.
Sub GetFromInbox()
Dim olApp As Outlook.Application
Dim olNs As Namespace
Dim Fldr As MAPIFolder
Dim olMail As Variant
Dim i As Integer
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
'Below is the line I have problem with
Set Fldr = olNs.GetDefaultFolder(olFolderInbox).Folders("PRE Customer")
i = 1
x = Date
For Each olMail In Fldr.Items
If InStr(olMail.Subject, "transactions") > 0 _
And InStr(olMail.ReceivedTime, x) > 0 Then
ActiveSheet.Cells(i, 1).Value = olMail.Subject
ActiveSheet.Cells(i, 2).Value = olMail.ReceivedTime
ActiveSheet.Cells(i, 3).Value = olMail.SenderName
i = i + 1
End If
Next olMail
Set Fldr = Nothing
Set olNs = Nothing
Set olApp = Nothing
End Sub
Just loop through all the folders in Inbox.
Something like this would work.
Edit1: This will avoid blank rows.
Sub test()
Dim olApp As Outlook.Application, olNs As Outlook.Namespace
Dim olFolder As Outlook.MAPIFolder, olMail As Outlook.MailItem
Dim eFolder As Outlook.Folder '~~> additional declaration
Dim i As Long
Dim x As Date, ws As Worksheet '~~> declare WS variable instead
Dim lrow As Long '~~> additional declaration
Set ws = Activesheet '~~> or you can be more explicit using the next line
'Set ws = Thisworkbook.Sheets("YourTargetSheet")
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
x = Date
For Each eFolder In olNs.GetDefaultFolder(olFolderInbox).Folders
'Debug.Print eFolder.Name
Set olFolder = olNs.GetDefaultFolder(olFolderInbox).Folders(eFolder.Name)
For i = olFolder.Items.Count To 1 Step -1
If TypeOf olFolder.Items(i) Is MailItem Then
Set olMail = olFolder.Items(i)
If InStr(olMail.Subject, "transactions") > 0 _
And InStr(olMail.ReceivedTime, x) > 0 Then
With ws
lrow = .Range("A" & .Rows.Count).End(xlup).Row
.Range("A" & lrow).Offset(1,0).value = olMail.Subject
.Range("A" & lrow).Offset(1,1).Value = olMail.ReceivedTime
.Range("A" & lrow).Offset(1,2).Value = olMail.SenderName
End With
End If
End If
Next i
Set olFolder = Nothing
Next eFolder
End Sub
Above takes care of all subfolders in Inbox.
Is this what you're trying?
To fix your error (olFolderInbox is a Outlook only constant, so you need to define it in vba that is not Outlook):
Const olFolderInbox = 6
'...
Set Fldr = olNs.GetDefaultFolder(olFolderInbox).Folders("PRE Customer")
Also to prevent missing Reference when run from another computer, I would:
Dim olApp As Object
Dim olNs As Object
Dim Fldr As Object
Dim olMail As Object
Dim i As Long
Set olApp = CreateObject("Outlook.Application")
'...
You might also want to disable ScreenUpdating, then enable it in Excel if you expect a long list.
UPDATE (Solution for all folders from a Root Folder)
I used something slightly different for comparing the dates.
Option Explicit
Private lRow As Long, x As Date, oWS As Worksheet
Sub GetFromInbox()
Const olFolderInbox = 6
Dim olApp As Object, olNs As Object
Dim oRootFldr As Object ' Root folder to start
Dim lCalcMode As Long
Set olApp = CreateObject("Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
Set oRootFldr = olNs.GetDefaultFolder(olFolderInbox).Folders("PRE Customer")
Set oWS = ActiveSheet
x = Date
lRow = 1
lCalcMode = Application.Calculation
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
GetFromFolder oRootFldr
Application.ScreenUpdating = True
Application.Calculation = lCalcMode
Set oWS = Nothing
Set oRootFldr = Nothing
Set olNs = Nothing
Set olApp = Nothing
End Sub
Private Sub GetFromFolder(oFldr As Object)
Dim oItem As Object, oSubFldr As Object
' Process all mail items in this folder
For Each oItem In oFldr.Items
If TypeName(oItem) = "MailItem" Then
With oItem
If InStr(1, .Subject, "transactions", vbTextCompare) > 0 And DateDiff("d", .ReceivedTime, x) = 0 Then
oWS.Cells(lRow, 1).Value = .Subject
oWS.Cells(lRow, 2).Value = .ReceivedTime
oWS.Cells(lRow, 3).Value = .SenderName
lRow = lRow + 1
End If
End With
End If
Next
' Recurse all Subfolders
For Each oSubFldr In oFldr.Folders
GetFromFolder oSubFldr
Next
End Sub

Resources