Link to home
Start Free TrialLog in
Avatar of JackVannoy
JackVannoy

asked on

Use VB6 to get information from MS Outlook

On a vb6 form we have a text box that contains an email address.  What we want to do is to double click on the text box and be able to view a list of all past email correspondence for the email address in the text box.

I can not seem to find the zone for Visual Basic 6, but that is what we are working with.

Any help will be grreatly appreciated.

Jack
Avatar of zhshqzyc
zhshqzyc

You can try this web site.vbforum.
A lot of vb6 experts and fans there.
http://www.slipstick.com/

Best resource for what your aiming for.
Avatar of JackVannoy

ASKER

Thanks for the quick response, however I should have been more specific. What we are looking for is some sample code.

Jack
Slipstick.com has more sample code on it than a sample code site :P

Use the links and do a spot of reading :D
Also would be helpful if you stated what version of Oulook? Is the textbox in an external application? Is exchange involved? etc...
Avatar of Chris Raisin
There is a great application that handles that exactly called NEOPRO
available from www.emailorganizer.com

However, sionce your question is specific, I am putting some code together for you.

Stand by....   :-)
This is VERY simple code that can be added to a project.

It uses a text box called txtText1 and a listbox called List1 (alter to names you prefer within your project)

When you type in an email address into the textbox then double click on it, it will go through the  "Inbox" of Outlook and find any emails which has been sent from that address and will add time sent and email title to the listbox.

That will give you a starting point for incorporating email queries into your application.

Use the debugger to look at the object "oEmail" to see all the values held in that object.

Enhancements could be to change the textbox to a combobox which will (on application start) load every address in the outlook list of addresses into the combobox The user could either select from the listing, or type it in.
(If this is chosen as an option I would suggest having a button next to the combobox to start the search for emails rather than double-clicking the combo-box)

Another enhancement could be to(when the user double-clicks an item in the Listbox) to  have the app bring up another box showing fuller details (even the body of the email) .

If you want me to expand on this simple code to do these things, let me know and I will do it to help you out.  :-)

Cheers
Chris
(craisin)
Option Explicit
Private Sub txtText1_DblClick()
  'Include in references a reference to: Microsoft Outlook 14.0 Object Library
  Dim oOutapp      As Outlook.Application
  Dim oNs          As Outlook.NameSpace
  Dim oMyInbox     As Outlook.MAPIFolder
  Dim oMyExplorer  As Outlook.Explorer
  Dim oEmail       As Variant
  
  Set oOutapp = New Outlook.Application
  Set oNs = oOutapp.GetNamespace("MAPI")
  Set oMyInbox = oNs.GetDefaultFolder(olFolderInbox)
  Set oMyExplorer = oMyInbox.GetExplorer
  Screen.MousePointer = vbHourglass
  For Each oEmail In oMyInbox.Items
    If LCase(oEmail.SenderEmailAddress) = LCase(txtText1.Text) Then
      List1.AddItem Format(oEmail.SentOn, "mm/dd/yy") + " - " + oEmail.Subject
    End If
  Next
  oMyExplorer.Close
  Screen.MousePointer = vbNormal
End Sub

Open in new window

Thank you Chris (craisin:)

Listed below is the code placed in our program

General Declarations

Option Explicit
   
'NOTE: in our project references, we are referencing Microsoft Outlook 12.0 Object Library.
'          Is that a problem?
      'Include in references a reference to:
      ' Microsoft Outlook 14.0 Object Library
 
     Dim oOutapp      As Outlook.Application
     Dim oNs          As Outlook.NameSpace
     Dim oMyInbox     As Outlook.MAPIFolder
     Dim oMyExplorer  As Outlook.Explorer
     Dim oEmail       As Variant

Private Sub EMail_txt_DblClick()

      List1.Clear
      Set oOutapp = New Outlook.Application
      Set oNs = oOutapp.GetNamespace("MAPI")
      Set oMyInbox = oNs.GetDefaultFolder(olFolderInbox)
      Set oMyExplorer = oMyInbox.GetExplorer

      Screen.MousePointer = vbHourglass
      For Each oEmail In oMyInbox.Items
        If LCase(oEmail.SenderEmailAddress) = LCase(EMail_txt.Text) Then
          List1.AddItem Format(oEmail.SentOn, "mm/dd/yy") + " - " & _
            oEmail.Subject
        End If
      Next
      oMyExplorer.Close
      Screen.MousePointer = vbNormal
End Sub

This works great for the (InBox).  What we are trying to accomplish is to get a list of all correspondence that deals with this email address, for all folders including date, subject and the body of data sent or received.

Another alternative that might work better is if the selected email address was delivered to Outlook and automatically be put into the (Search Mode) for all folders for the email address.  That way the user could just move up or down on the display and see the displayed body of data.

Chris, I really do appreciate your response and your offer to help further.

Jack

Jack,

Have you considered using NEOPRO? That product certainly will do everything you want (and heaps more). (I can't live without it).

Anyway, I will do some more work on the code as you have submitted and incorporte what you are after.

Stand by....
BTW, the reference to 12 is  OK - that indicates you are using Outlook 2003, am I correct?

I am using Outlook 2010 but it will work the same way.
The code has been tweaked to produce something which is more like what you are after.

Nore: Change the text field for input to a combo-box with the settings as shown below
ComboBox.jpg
And here is the code....you may need to tweak it to fit into your application....

If you only want to search on email addresses then it becomes a little more complicated (we will have to use the Advanced Search Panel within Outlook), but that is possible.

Note: You can enter ANY words into the combobox (not just email addresses)
but the drop-down box will only highlight email addresses which are in your Contacts. Upper or lower case is unimportant.

If this does not work at your end, it may be due to differences in versions of  Outlook.  I can switch to Version 2003 if needed (I have both 2003 and 2010).

Let me know if this is closer to the mark.

Cheers
Chris
Option Explicit
'Include in references a reference to: Microsoft Outlook 12.0 Object Library

'This application simply accepts any words (e.g. an email address)
'and then searches through outlook for those words
'This COULD be refined to only search for email addresses, but the added
'functionality might come in handy!

Private oOutapp      As Outlook.Application
Private oNs          As Outlook.NameSpace
Private oMyInbox     As Outlook.MAPIFolder
Private oMyAddresses As Outlook.MAPIFolder
Private oMyExplorer  As Outlook.Explorer
Private oEmail       As Variant
Private oAddress     As Variant
Private bDropped     As Boolean   'flag used to decide if the combo box is in dropped mode

Const CB_ERR = -1
Const CB_FINDSTRING = &H14C
Private Sub Form_KeyPress(Keyascii As Integer)
  If Keyascii = vbKeyEscape Then
    bDropped = False
    Email_cmb.Text = ""
    Email_cmb.SetFocus
    SendKeys "{F4}", True
  End If
End Sub
Private Sub Form_activate()
  Email_cmb.Text = ""
End Sub
Private Sub Form_Load()
  Set oOutapp = New Outlook.Application
  Set oNs = oOutapp.GetNamespace("MAPI")
  Set oMyAddresses = oNs.GetDefaultFolder(olFolderContacts)
  Set oMyInbox = oNs.GetDefaultFolder(olFolderInbox)
  For Each oAddress In oMyAddresses.Items
    If oAddress.Class <> olDistributionList Then
      If Len(oAddress.Email1Address) > 0 Then
        Me.Email_cmb.AddItem oAddress.Email1Address
      End If
      If Len(oAddress.Email2Address) > 0 Then
        Me.Email_cmb.AddItem oAddress.Email2Address
      End If
      If Len(oAddress.Email3Address) > 0 Then
        Me.Email_cmb.AddItem oAddress.Email3Address
      End If
    End If
  Next
End Sub
Private Sub Email_cmb_KeyPress(Keyascii As Integer)
  Set oMyExplorer = oMyInbox.GetExplorer
  If Keyascii = vbKeyEscape Then
    End
  Else
    If Not bDropped And Len(Email_cmb.Text) = 0 Then
      bDropped = True
      SendKeys "{F4}", True
    End If
    If Keyascii = vbKeyReturn Then
      oMyExplorer.ClearSearch
      oMyExplorer.Search Email_cmb.Text, olSearchScopeAllFolders
      oMyExplorer.Activate
      oMyExplorer.Display
    Else
      sMatchEntry Email_cmb, Keyascii
    End If
  End If
End Sub
Sub sMatchEntry(cbo As ComboBox, Keyascii As Integer)
  Dim sBuffer As String
  Dim lRetVal As Long
  sBuffer = Left(cbo.Text, cbo.SelStart) & Chr(Keyascii)
  lRetVal = SendMessage((cbo.hWnd), CB_FINDSTRING, -1, ByVal sBuffer)
  If lRetVal <> CB_ERR Then
    With cbo
      .ListIndex = lRetVal
      .Text = .List(lRetVal)
      .SelStart = Len(sBuffer)
      .SelLength = Len(.Text)
    End With
    Keyascii = 0
  End If
End Sub

Open in new window

Oh, and the listbox is now gone (we don't really need it)  :-)

Cheers
Chris
I have found a problem after we look at the first Outlook search and close it.

That closes the reference to oMyExplorer and we cannot use it again.

Stand by while I fix.....
Success!

Use the code showing below instead.

Remember to change text box to ComboBox with settings showing above.

Starting to look good!  :-)
Option Explicit
'Include in references a reference to: Microsoft Outlook 12.0 Object Library

'This application simply accepts any words (e.g. an email address)
'and then searches through outlook for those words
'This COULD be refined to only search for email addresses, but the added
'functionality might come in handy!

Private oOutapp      As Outlook.Application
Private oNs          As Outlook.NameSpace
Private oMyInbox     As Outlook.MAPIFolder
Private oMyAddresses As Outlook.MAPIFolder
Private oEmail       As Variant
Private oAddress     As Variant
Dim oMyExplorer      As Outlook.Explorer
Private bDropped     As Boolean   'flag used to decide if the combo box is in dropped mode

Const CB_ERR = -1
Const CB_FINDSTRING = &H14C
'Private Sub Form_KeyPress(Keyascii As Integer)
'  If Keyascii = vbKeyEscape Then
'    bDropped = False
'    Email_cmb.Text = ""
'    Email_cmb.SetFocus
'    SendKeys "{F4}", True
'  End If
'End Sub
Private Sub Form_activate()
  Email_cmb.Text = ""
  Email_cmb.SetFocus
  bDropped = True
  SendKeys "{f4}", True
End Sub

Private Sub Form_Load()
  Set oOutapp = New Outlook.Application
  Set oNs = oOutapp.GetNamespace("MAPI")
  Set oMyAddresses = oNs.GetDefaultFolder(olFolderContacts)
  For Each oAddress In oMyAddresses.Items
    If oAddress.Class <> olDistributionList Then
      If Len(oAddress.Email1Address) > 0 Then
        Me.Email_cmb.AddItem oAddress.Email1Address
      End If
      If Len(oAddress.Email2Address) > 0 Then
        Me.Email_cmb.AddItem oAddress.Email2Address
      End If
      If Len(oAddress.Email3Address) > 0 Then
        Me.Email_cmb.AddItem oAddress.Email3Address
      End If
    End If
  Next
  
End Sub
Private Sub Email_cmb_KeyPress(Keyascii As Integer)
  Set oOutapp = New Outlook.Application
  Set oNs = oOutapp.GetNamespace("MAPI")
  Set oMyAddresses = oNs.GetDefaultFolder(olFolderContacts)
  Set oMyInbox = oNs.GetDefaultFolder(olFolderInbox)
  If Keyascii = vbKeyEscape Then
    If Len(Email_cmb.Text) = 0 Then
      End
    Else
      Email_cmb.Text = ""
      bDropped = False
    End If
  Else
    'If Not bDropped And Len(Email_cmb.Text) = 0 Then
    If Not bDropped Then
      bDropped = True
      SendKeys "{F4}", True
    End If
    If Keyascii = vbKeyReturn Then
      Set oMyExplorer = oMyInbox.GetExplorer
      oMyExplorer.Search Email_cmb.Text, olSearchScopeAllFolders
      oMyExplorer.Display
      bDropped = False 'to force dropdown when returning to combobox
    Else
      sMatchEntry Email_cmb, Keyascii
    End If
  End If
End Sub
Sub sMatchEntry(cbo As ComboBox, Keyascii As Integer)
  Dim sBuffer As String
  Dim lRetVal As Long
  sBuffer = Left(cbo.Text, cbo.SelStart) & Chr(Keyascii)
  lRetVal = SendMessage((cbo.hWnd), CB_FINDSTRING, -1, ByVal sBuffer)
  If lRetVal <> CB_ERR Then
    With cbo
      .ListIndex = lRetVal
      .Text = .List(lRetVal)
      .SelStart = Len(sBuffer)
      .SelLength = Len(.Text)
    End With
    Keyascii = 0
  End If
End Sub

Open in new window

Thank you again Chris (craisin

I have placed the code into my project and I have a few questions.  

1. When I try to run the program in vb6 basic code, I get a (Permission Denied error) at the SendKeys "{F4}", True.  I have encountered this in other programs where I attempted to use SendKeys and never did figure out the reason for the error.

2. Not sure why we need the combo box instead of just using the (Dbl Click) on a text box that contains the email address we are interested in for a specific customers email data.

3. When I Rem out the Send Keys, I do get a list in the combo box, and when pressing the (Enter) key I do go to the Outlook search routine, but nothing is displayed.  Is this maybe because of the Send Keys problem?

Chris, I know you are spending a lot of time on this for me, and I hope I am not asking too much.

Jack
1. All the F4 does is causes the CoboBox to drop down. If you do not have a combo box then the F4 will be sent elsewhere, and I cannot say what is sending back the error.  Perhaps you have 1 hotkey on your desktop that is intercepting it.
If you DO have a combobox, the the combobox does not have focus when the "Sendkeys" goes to it, and we will have to investigate why.

2. I set it as a combobox because the code then loads every email address you have in your Outlook into the combobox. Then as you type, it will find the email address for you and you do not have to type the entire address (also avoids typo errors). Remember, as it is, the combobox will accept any value.
If we leave it as a textbox yu run the risk of typing errors and also it is tedious sometimes typing a full email address. Give the combo box a go first and if it is not to your liking (goodeness knows why) I can change back to textbox code.

3. You must have a value typed into the combobox, start typing and when the correct email address appears in the combox where you cursor lies, hit enter.
Now, I am using Outlook 2010 and what happens there is that the email address in the combobox is transferred automatically over into Outlooks "Search" box, and outlook starts looking for all emails containing that email address anyhere in it.
(Note, the address could be "Sent By", "Sent To" or may even appear in the text of a message. I stated earlier that this process at the moment is simply looking for all messages containg the text entered into the combobox. If you want it to relate ONLY to "Sender" and "SentTo" fields, we will have to program differently (much more difficult).

I suspect the problems you are encountering may have to do with the version of Outlook you are using. Please confirm version.

If you are using 2003 I can help (since I have that version too). I hope it is not version dependent since it is messy moving back from Version 2010 to 2003.
If you have version 2007 I cannot help track the problem down at my end, but we may be able to do it at your end with some help stepping through the debigger.

Please advise situation.

Cheers
Chris
Chris, thanks for your prompt response.

AT the moment, I am getting pulled away for a small project that may take the rest of the day.  Tommorow, I will read your last response, and get back to you then.

Jack

Hi Chris

The version of outlook on my computer is 2007.  I have a computer here that has 2003.  Today I will transfer the project to the other computer and see if it makes a difference.

In answer to your question as to why not use a combo box instead of the text box. Our programs are for Heating and Cooling Contractors, and some of them may have 2 or 3 thousand customers.  What they are asking for is that when they bring up a customer in our (Customer File Maintenance) screen, and their customer's email address is automatically displayed in the Email_txt text box, they just want to double click that box, and have Outlook display all of the correspondence (Send or Receive) for that specific email address.

Will get back to you a little later.

Jack
Hi Chris

I am listing all of the code that we now have in our program regarding the email.  We are getting the emails for the t email address, that is in the (Email_txt.Text), from all of the  (Personal Folders) including the (InBox), but nothing from the (Deleted Items).

Option Explicit
   
    Private oOutapp      As Outlook.Application
    Private oNs          As Outlook.NameSpace
    Private oMyInbox     As Outlook.MAPIFolder
    Private oMyDeletedItems   As Outlook.MAPIFolder          ' Maybe in
    'Private oMyAddresses As Outlook.MAPIFolder         'Maybe out
    Private oEmail       As Variant
    Private oAddress     As Variant
    Dim oMyExplorer      As Outlook.Explorer
    '==========================================================================

Private Sub EMail_txt_DblClick()

    Set oOutapp = New Outlook.Application
    Set oNs = oOutapp.GetNamespace("MAPI")
    'Set oMyAddresses = oNs.GetDefaultFolder(olFolderContacts) 'Maybe do not need
    Set oMyInbox = oNs.GetDefaultFolder(olFolderInbox)
    Set oMyExplorer = oMyInbox.GetExplorer
   
    Set oMyDeletedItems = oNs.GetDefaultFolder(olFolderDeletedItems) 'Maybe can use this
    Set oMyExplorer = oMyDeletedItems.GetExplorer                    'Maybe can use this
   
    oMyExplorer.Search EMail_txt.Text, olSearchScopeAllFolders
    oMyExplorer.Display

End Sub

We would like to get all correspondence from the deleted items if it is possible.

NOTE: all of the above code is still on the computer with Outlook 2007. There is a problem to talk about when this code is run on the compter with Outlook 2003.

Will appreciate any help you can give

Jack
So you don't want to go with the combobox? (I thought it was pretty nifty, actually).
OK...It is very simple, really.

Using just your code, I have tweaked it slightly.
Option Explicit
Private oOutapp      As Outlook.Application
Private oNs          As Outlook.NameSpace
Private oMyInbox     As Outlook.MAPIFolder
Dim oMyExplorer      As Outlook.Explorer
Private Sub EMail_txt_DblClick()
  Set oOutapp = New Outlook.Application
  Set oNs = oOutapp.GetNamespace("MAPI")
  Set oMyInbox = oNs.GetDefaultFolder(olFolderInbox)
  Set oMyExplorer = oMyInbox.GetExplorer
  oMyExplorer.Search Email_txt.Text, olSearchScopeAllFolders
  oMyExplorer.Display
End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Chris Raisin
Chris Raisin
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Chris

Thanks again for your quick response.

Actually the Combo box routine is really great, it just wasn't what our client requested. We will definitely hold on to that code for future enhancements.

The code now in our program is displayed below and works fine for everything except it still is not returning anything from the (Deleted) folder. Can this be accomplished?  Also it is returning all correspondence for any word contained in the (Email Address). EXAMPLE;  jack@cucsoft.com will return any correspondence that has the word (jack), or (cucsoft), or (com) any where in the body of the email. IIs there anyway around this?  

In the  Private Sub EMail_txt_DblClick() code, please note the
rem'd remarks.
=============================================
Option Explicit
    Private oOutapp      As Outlook.Application
    Private oNs          As Outlook.NameSpace
    Private oMyInbox     As Outlook.MAPIFolder
    Dim oMyExplorer      As Outlook.Explorer
=============================================

=============================================
   Private Sub EMail_txt_DblClick()

    Set oOutapp = New Outlook.Application
    Set oNs = oOutapp.GetNamespace("MAPI")
    Set oMyInbox = oNs.GetDefaultFolder(olFolderInbox)
    Set oMyExplorer = oMyInbox.GetExplorer
   
    'The line below must work in your Outlook 2010, but not in my Outlook 2007
    'oMyExplorer.Search EMail_txt.Text, olSearchScopeAllOutlookItems
   
    'The line below works in my Outlook 2007, but is not available in Outlook 2003
    oMyExplorer.Search EMail_txt.Text, olSearchScopeAllFolders
   
    oMyExplorer.Display

End Sub
================================================

Jack
Yes, that can be accomplished.

I hope I am not just doing some work here for a contract job for which you are being paid? I am not sure whether Experts Exchange is designed to take away potential contract work from hard working programmers out in the field. (I am a retired programmer).

I will, however, assume that all is kosher, and will incorporate your requests.
It SHOULD be showing up emails in the DELETED folder (mine does), so that may take some investigation.

I assume that the procedure is only scanning the local users folders. I am not sure that it should be allowed to scan other users folders on the system (security) or even whether that is possible.

Stand by..... (might take a few hours since I am recovering from an accident and will be going for X-Rays this afternoon)

Cheers
Chris
Aaah! I just saw why your "deleteds"  email is not being picked up.

"olSearchScopeAllFolders" looks only in Mail Folders (DELETED is not included)
whereas "olSearchScopeAllOutlookItems" searches through everything to do with email. (including deleteds).

I will investogate whether there is an equivalent method in Outlook 2003 which may then work in 2007.

Stand by....

Thank you very much Chris (craisin

Your help has been really great, best I have ever had.  I am accepting one of your responses as the soulution.

Jack

Great responses, and very much appreciated.

Jack
Jack, did you get around the "deleteds" problem in Outlook 2003?

Cheers
Chris
Sorry...I meant Outlook 2007

:-)
Hi Chris

Actually I upated my computer to Outlook 2010. The code is as listed below, which I think is the same as your last response except that I moved the action to a (Command) button.

It works fine for the (Personal Folders), the (Inbox), and the (Sent Items).  Still not bringing anything from the (Deleted Items).  I closed the question because I wasn't sure whether the (Deleted Items) were that important or not.

I am curious as to why it did not pick up the (Deleed Iems)  as the code seems correct to me.
Also, it does'nt seem to work in Outlook 2007 on anything except (Personal Folders).

I am happy with the results that we did achieve, however If you want to persue this further, let me know and I can post a related question and assign points.

Jack


Option Explicit
    '=== For accessing all correspondence for a specifice email address ==================
    Private oOutapp      As outlook.Application
    Private oNs          As outlook.NameSpace
    Private oMyinbox     As outlook.MAPIFolder
    Dim oMyExplorer      As outlook.Explorer
    '==========================================================================

Private Sub SeeEmailInfo_btn_Click()
 
    If Trim(EMail_txt.Text) = "" Then
        MsgBox "No email address assigned to this customer", vbOKOnly
        Exit Sub
    End If
   
    Set oOutapp = New outlook.Application
    Set oNs = oOutapp.GetNamespace("MAPI")
    Set oMyinbox = oNs.GetDefaultFolder(olFolderInbox)
    Set oMyExplorer = oMyinbox.GetExplorer
    oMyExplorer.Search EMail_txt.Text, olSearchScopeAllOutlookItems
   
End Sub

OK...Standby before you open a related question...I think that it was picking up deleted items on my system under 2010 but I need to confirm that first.

Will get back to you shortly.

Cheers
Chris
Don't forget the line

     oMyExplorer.Display

at the end of your "SeeEmailInfo_btn_Click" procedure.

OK I have the answer for you regarding deleted items.

Please opn a related question and I will post the change in the code.

Cheers
Chris

Please stand by again...The code you gave about DOES show deleted items as well as others on my system.

Jack,

Alright...after much research I have come across a possible reason why the deleted items are not being included.

Please open a rtelated question and I will answer there.

I suppose that you are still getting every email that includes the email address ANYWHERE in the message (e.g. Sender/Receiver or even those with the email address quoted in the body of the message).
If that is so, that is probably not exactly what you wanted (but even a reference to the emailin the body of a message  might be helpful for your client).

I await your further action.

Cheers
Chris