Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting Outlook Email with VB.NET 1

Status
Not open for further replies.

BG12424

Programmer
Jun 4, 2002
717
US
I've posted in the Office Forum thread68-731432, but not sure which forum would help most.

I am able to pull back emails in my Outlook Inbox with the following code, however, if the email has no subject line, I get an invalid cast exception. Can anyone take a look at the code below and help me get through this? Thanks

Code:
        Dim olApp As Outlook.Application = New Outlook.Application()
        Dim olNS As Outlook.NameSpace = olApp.GetNamespace("MAPI")
        olNS.Logon("Brian Gaines", "", False, True)
        Dim olInbox As Outlook.MAPIFolder = olNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
        Dim olItems As Outlook.Items = olInbox.Items
        Dim i As Integer
        Try
            If olItems.Count > 0 Then
                ListBox1.Items.Clear()
                For i = 1 To olItems.Count
                    Dim email As Outlook.MailItem = olItems.Item(i)

                    ListBox1.Items.Add(email.Subject & " >>> FROM: " & email.SenderName)
                Next
                Label1.Text = "Emails: " & (i - 1).ToString
                olNS.Logoff()
            End If
        Catch ex As Exception
            lblMessage.Text = ex.ToString
        Finally
            olApp = Nothing
            olNS = Nothing
            olItems = Nothing
            olInbox = Nothing
        End Try


regards,
Brian
 
The absolute best place for vb outlook integration is


You will find almost everything you need to know there.

You are most likely getting the invalid case because when there is no subject it returns Null or Nothing and you are trying to concatanate it with a string as below.

ListBox1.Items.Add(email.Subject & " >>> FROM: " & email.SenderName)

The & cannot conntet the Null or Nothing to the String. You would need to check the value first.

Also:


If you add the reference to you project you can use early binding like below. This code will get the Subject among other things.(It will be much eaiser to read if you copy/Paste it into a project)

Dim objOutlook As Outlook.Application
Dim objNamespace As Outlook.NameSpace
Dim objMAPIFolder As Outlook.MAPIFolder
objOutlook = New Outlook.Application()
' Get Mapi NameSpace.
Dim oNS As Outlook.NameSpace = objOutlook.GetNamespace("mapi")
oNS.Logon("test", "test", True, True)

Dim oInbox As Outlook.MAPIFolder = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)

Dim oItems As Outlook.Items = oInbox.Items

Dim MoveToFldr As Outlook.MAPIFolder = oInbox.Folders.Item("Large Messages")
'Dim MoveToFldr2 As Outlook.MAPIFolder = oNS.Folders.Item("Personal Folders").Folders.Item("Inbox").Folders.Item("Large Messages")


' Get unread e-mail messages.
'oItems = oItems.Restrict("[Unread] = true")

Dim i As Integer
Dim oMsg As Outlook.MailItem
Dim cnt As Integer = oItems.Count
For i = cnt To 1 Step -1

oMsg = oItems.Item(i)
'Mail Information
Dim myTest As String = oMsg.Subject


Dim OutlookEntryID As String = oMsg.EntryID
Dim ReceivedTime As String = oMsg.ReceivedTime
Dim fldCCd As String = oMsg.CC
Dim fldBCCd As String = oMsg.BCC

Next

DotNetDoc
M.C.S.D.
---------------------------------------

Tell me and I forget. Show me and I remember. Involve me and I understand.
- Anonymous Chinese Proverb
-----------------------------------
If you can't explain it simply, you don't understand it well enough.
- A. Einstein
 
I use a product from Chilkat software, and it's easy, cheap, and works great.
 
They are both based on Mapi folders. I am not sure of the dll you would need to reference for express.

DotNetDoc
M.C.S.D.
---------------------------------------

Tell me and I forget. Show me and I remember. Involve me and I understand.
- Anonymous Chinese Proverb
-----------------------------------
If you can't explain it simply, you don't understand it well enough.
- A. Einstein
 
Thanks DotNetDoc, I've checked-out the slipstick website, but not sure which area of the site I need to look for for this. Thanks for your example code.


regards,
Brian
 
You would want to click on the Developers tab.

DotNetDoc
M.C.S.D.
---------------------------------------

Tell me and I forget. Show me and I remember. Involve me and I understand.
- Anonymous Chinese Proverb
-----------------------------------
If you can't explain it simply, you don't understand it well enough.
- A. Einstein
 
devmail has a product that can be used in freemode, the full mode is about $350 for a single developers license.

I am thinking I should learn to make custom controls enstead of programs :)




Becca

Somtimes, the easy answer is the hardest to find. :)

Still under construction ...
 
Becca/Bigfoot,

I'm not sure what you are referring to. The code syntax that I was going after is for a windows service that I am creating which will monitor an inbox using Exchange/Outlook. 3rd Party tools are out of question in my case since we are a major regulator with high level of security and many custom processes that a typical out-of-box solution will not provide. Thanks


regards,
Brian
 
I am getting a "specified cast is not valid" exception when I get to the specified code below. Can someone lend any insight on how to correct this? Thanks

Try
Dim olApp As Outlook.Application = New Outlook.Application
Dim olNS As Outlook.NameSpace = olApp.GetNamespace("MAPI")
Dim olInbox As Outlook.MAPIFolder = olNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
olNS.Logon(Nothing, Nothing, False, True)
Dim olItems As Outlook.Items = olInbox.Items
Dim email As Outlook.MailItem
Dim boxCount As Integer = olItems.Count
Dim i As Integer

Try
For i = boxCount To 1 Step -1

===============>>>> Exception is kicked off on next line.
email = olItems.Item(i)


Dim matchValue As String = RegExValue(email.Subject, "Undeliverable")
Dim invalidEmail As String = RegExValue(email.body, "\b[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+\.[a-zA-Z0-9._%-]{2,4}\b")
If matchValue.Length = 0 Then
email.Delete()
Else
lbInboxPrototype.Items.Add(email.Subject & " >>> " & invalidEmail)
End If
Next
olNS.Logoff()
Catch ex As Exception
txtException.Text = ex.ToString
txtException.Visible = True
Finally
olApp = Nothing
olNS = Nothing
olItems = Nothing
olInbox = Nothing
End Try

Catch outEx As Exception
txtException.Text = outEx.ToString
txtException.Visible = True
End Try



regards,
Brian
 
Lots of useful info in the thread.

One thing that specifically helped me, and I'd thought I'd mention for anyone else who has similar problems, is this:
I kept getting "index out of bounds" errors when trying to read 2+ emails. The solution was to iterate though the emails in descending order as in the examples above. (count to 1 step -1)

I do not know why it works this way and not forward but it does!
 
Well, it's been awhile, but I got this code working awhile back. Since someone has posted to this thread, I will add the final code that I have for this.

Code:
    Sub RunThroughInbox(ByVal sender As Object, _
                            ByVal e As ElapsedEventArgs) _
                            Handles cbInboxTimer.Elapsed
        Try
            If profile.RunService Then
                If profile.WriteServiceRunningMessageToLog Then
                    EventLog.WriteEntry("NECSInBox", profile.GetServiceRunningMessage)
                End If

                Dim olApp As Outlook.Application = New Outlook.Application
                Dim olNS As Outlook.NameSpace = olApp.GetNamespace("MAPI")
                olNS.Logon(profile.GetDefaultMailProfile, Missing.Value, False, True)

                Dim olIn As Outlook.MAPIFolder = olNS.Folders.Item(profile.GetNecsMailbox)
                Dim olInbox As Outlook.MAPIFolder = olIn.Folders.Item(profile.GetNecsMailboxInbox)

                Dim olItems As Outlook.Items = olInbox.Items
                Dim boxCount As Integer = olItems.Count
                Dim i As Integer
                Dim cnt As Integer = 0
                Dim delKey As Integer
                '********************
                'Dim strMessage As String
                '********************

                Try

                    For i = boxCount To 1 Step -1

                        Dim err As String = ""
                        Dim keyIndexSubject As String = String.Empty
                        Dim keyIndexBody As String = String.Empty
                        Dim emailSubject As String = olItems.Item(i).Subject
                        Dim receiptBody As String = olItems.Item(i).Body

                        'Check for message that get deleted.
                        delKey = 1
                        keyIndexSubject = ContainsValue(_deleteMessages, emailSubject)
                        keyIndexBody = ContainsValue(_deleteMessages, receiptBody)
                        'If no deleted flags, check for messages that get marked.
                        If keyIndexBody Is String.Empty Then
                            keyIndexBody = ContainsValue(_strikeMessages, receiptBody)
                        Else
                            delKey = -1
                        End If

                        If keyIndexSubject Is String.Empty Then
                            keyIndexSubject = ContainsValue(_strikeMessages, emailSubject)
                        Else
                            delKey = -1
                        End If

                        If TypeOf olItems.Item(i) Is Outlook.ReportItem Then
                            cnt += 1
                            Dim report As Outlook.ReportItem = CType(olItems.Item(i), Outlook.ReportItem)
                            If report.Attachments.Count > 0 Then
                                Dim returnedEmail As Outlook.Attachment = report.Attachments.Item(1)
                                returnedEmail.SaveAsFile("c:\" & returnedEmail.FileName)
                                Dim emailBody = GetMessageBody("c:\" & returnedEmail.FileName, err)

                                If err = "" Then
                                    Dim key As String = GetKeyName(String.Empty, keyIndexBody)
                                    Dim invalidEmail As String = RegExValue(emailBody, profile.GetInboxEmailRegExPattern)
                                    Dim matchGuid As String = RegExValue(emailBody, profile.GetInboxGuidRegExPattern)

                                    If Not matchGuid Is String.Empty Then
                                        Dim parsedSubject = emailSubject.Replace("Undeliverable:", String.Empty).Trim
                                        SaveReturnedEmails(matchGuid, invalidEmail, parsedSubject, receiptBody, -1)
                                        olItems.Item(i).Delete()
                                        File.Delete("c:\" & returnedEmail.FileName)
                                        'strMessage = "DELETED: :keyIndexSubject:  " & keyIndexSubject & "  :keyIndexBody:  " & keyIndexBody & " :delKey:  " & delKey & " :Email:  " & invalidEmail & " :GUID: " & matchGuid
                                        'EventLog.WriteEntry("NECSInBox", strMessage)
                                    Else
                                        If Not keyIndexSubject Is String.Empty Or Not keyIndexBody Is String.Empty Then
                                            'strMessage = "MOVED: :keyIndexSubject:  " & keyIndexSubject & "  :keyIndexBody:  " & keyIndexBody & " :delKey:  " & delKey & " :Email:  " & invalidEmail & " :GUID: " & matchGuid
                                            'EventLog.WriteEntry("NECSInBox", strMessage)
                                            MoveMailMessageForReview(olInbox, olItems, i)
                                        End If
                                    End If
                                End If
                            Else
                                Dim key As String = GetKeyName(String.Empty, keyIndexBody)
                                Dim invalidEmail As String = RegExValue(report.Body, profile.GetInboxEmailRegExPattern).Trim
                                Dim matchGuid As String = RegExValue(report.Body, profile.GetInboxGuidRegExPattern).Trim
                                Dim subject As String = RegExValue(report.Body, profile.GetSubjectFromMessageRegExPattern).Trim
                                If matchGuid = String.Empty And Not subject = String.Empty Then
                                    matchGuid = GetGuidFromSubject(subject)
                                End If
                                If Not matchGuid = String.Empty And Not subject = String.Empty Then
                                    SaveReturnedEmails(matchGuid, invalidEmail, subject, report.Body, -1)
                                    olItems.Item(i).Delete()
                                Else
                                    MoveMailMessageForReview(olInbox, olItems, i)
                                End If
                            End If
                        ElseIf TypeOf olItems.Item(i) Is Outlook.MailItem Then
                            If Not keyIndexBody Is String.Empty Or Not keyIndexSubject Is String.Empty Then
                                Dim mail As Outlook.MailItem = olItems.Item(i)
                                Dim invalidEmail As String = RegExValue(mail.Body, profile.GetInboxEmailRegExPattern)
                                Dim matchGuid As String = RegExValue(mail.Body, profile.GetInboxGuidRegExPattern)
                                If matchGuid Is String.Empty Or invalidEmail Is String.Empty Then
                                    Dim attachCount As Integer = mail.Attachments.Count
                                    Dim x As Integer = 1
                                    If attachCount > 0 Then
                                        Do While (x < attachCount + 1) Or (keyIndexSubject Is String.Empty And keyIndexBody Is String.Empty)
                                            Dim mailAttach As Outlook.Attachment = mail.Attachments.Item(x)
                                            If matchGuid Is String.Empty And mailAttach.FileName.EndsWith("msg") Then
                                                matchGuid = GetGuidFromSubject(mailAttach.FileName)
                                            Else
                                                mailAttach.SaveAsFile("c:\" & mailAttach.FileName)
                                                Dim attachBody = GetMessageBody(GetFileAttachmentName(x), err)
                                                If invalidEmail Is String.Empty Then
                                                    invalidEmail = RegExValue(attachBody, profile.GetInboxEmailRegExPattern)
                                                End If
                                                If matchGuid Is String.Empty Then
                                                    matchGuid = RegExValue(attachBody, profile.GetInboxGuidRegExPattern)
                                                End If
                                                File.Delete("c:\" & mailAttach.FileName)
                                                x += 1
                                            End If
                                        Loop
                                    Else
                                        'No Attachments....  No guid.... look for subject in text of email.
                                        Dim newSubject As String = RegExValue(mail.Body, profile.GetSubjectFromMessageRegExPattern)
                                        If Not newSubject Is String.Empty Then
                                            matchGuid = GetGuidFromSubject(newSubject)
                                        End If
                                    End If
                                End If
                                If Not matchGuid Is String.Empty And Not invalidEmail Is String.Empty Then
                                    Dim parsedSubject = emailSubject.Replace("Undeliverable:", String.Empty).Trim
                                    SaveReturnedEmails(matchGuid, invalidEmail, parsedSubject, receiptBody, -1)
                                    olItems.Item(i).Delete()
                                    'strMessage = "DELETED: :keyIndexSubject:  " & keyIndexSubject & "  :keyIndexBody:  " & keyIndexBody & " :delKey:  " & delKey & " :Email:  " & invalidEmail & " :GUID: " & matchGuid
                                    'EventLog.WriteEntry("NECSInBox", strMessage)
                                Else
                                    If Not keyIndexSubject Is String.Empty Or Not keyIndexBody Is String.Empty Then
                                        'strMessage = "MOVED: :keyIndexSubject:  " & keyIndexSubject & "  :keyIndexBody:  " & keyIndexBody & " :delKey:  " & delKey & " :Email:  " & invalidEmail & " :GUID: " & matchGuid
                                        'EventLog.WriteEntry("NECSInBox", strMessage)
                                        MoveMailMessageForReview(olInbox, olItems, i)
                                    End If
                                End If
                            End If
                        Else
                            MoveMailMessageForReview(olInbox, olItems, i)
                        End If
                    Next i

                Catch ex As Exception
                    WriteToEventLog(ex.ToString)
                Finally
                    olNS.Logoff()
                    olApp = Nothing : olNS = Nothing
                    olItems = Nothing : olInbox = Nothing
                    If profile.WriteServiceTotalUndeliveredEmailsToLog Then
                        WriteToEventLog(profile.GetTotalUndeliveredEmailsMessage.Replace("?", cnt))
                    End If
                End Try
            Else
                If profile.WriteServicePauseMessageToLog Then
                    WriteToEventLog(profile.GetServicePauseMessage)
                End If
            End If
        Catch outEx As Exception
            WriteToEventLog(outEx.ToString)
        End Try
    End Sub

regards,
Brian
The problem with doing something right the first time is that nobody appreciates how difficult it was.
 
Hi peoples

I have used some of your code but an error occurs on the following line:-

olNS.Logon(UserName, Password, False, True)

System.Runtime.InteropServices.COMException (0x84170057): Could not complete the operation. One or more parameter values are not valid. at Microsoft.Office.Interop.Outlook.NameSpaceClass.Logon(Object Profile, Object Password, Object ShowDialog, Object NewSession) at TestWeb.WebForm1.testing() in c:\inetpub\ 167
 
Are you importing the System.Reflection namespace?

regards,
Brian
The problem with doing something right the first time is that nobody appreciates how difficult it was.
 
As in Imports System.Reflection such as this?

I was wondering how does it know what exchange server to go to we have 7 email servers here, wouldnt i have to assign it to one or will it just find?

The error has changed to:-System.Runtime.InteropServices.COMException (0x84140111): The server is not available. Contact your administrator if this condition persists. at Microsoft.Office.Interop.Outlook.NameSpaceClass.Logon(Object Profile, Object Password, Object ShowDialog, Object NewSession) at TestWeb.WebForm1.testing() in c:\inetpub\ 166

I am assumming username is domainname\username?
 
Yes...

Remember, that this code runs through the Outlook Inbox not Exchange, so I believe that whatever server your Outlook client is hitting would be the Exchange server that is used. Maybe a dumb question, but do you have MS Outlook set up on the computer where you are running this code?

regards,
Brian
The problem with doing something right the first time is that nobody appreciates how difficult it was.
 
username and password is the mail profile and password. On mine, I just had to add my name.

regards,
Brian
The problem with doing something right the first time is that nobody appreciates how difficult it was.
 
now its throwing an the following error

System.Runtime.InteropServices.COMException (0x80010105): The server threw an exception. at Microsoft.Office.Interop.Outlook.NameSpaceClass.Logon(Object Profile, Object Password, Object ShowDialog, Object NewSession) at TestWeb.WebForm1.testing(String strName) in c:\inetpub\ 166
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top