How can I download attachments using EWS (Exchange Web Services) in VB .NET

Morning All,

I am really hoping somebody can help me here.

I have a mechanism that downloads attachments from email messages sent into an inbox to a folder for processing by another service.

Originally this was done using some VBA that was triggered by a rule in Outlook. This wasn't build with large amounts of information going in originally however it has got to the point now that lots of data is being passed through and it is causing me headaches using this Outlook VBA and SSIS Package combination.

Therefore I am working on a new version built entirely in VB .NET, this obviously will mean its more robust and a lot easier to debug problems.

I have started using the EWS API and have managed to successfully connect to the Exchange and I am able to read the relevant messages and store their Subject etc. to variables.

I am struggling however to find ANY documentation / help regarding downloading of attachements with EWS with VB .NET code.

Everything seems to be in C# and I unfortunately have no experience with this. I am totally open to 3rd Party Solutions that may need to be purchased or even pointed in the right direction of a book or documentation, this is not being done on a shoe string and is quite important.

Any assistance in any way shape or form would be GREATLY appreciated.

Cheers,

James
Lynchie435Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bob LearnedCommented:
First of all, which version of EWS are you using?
0
Lynchie435Author Commented:
Hi Bob,

I am using EWS 2.2.

Regards,

James
0
Bob LearnedCommented:
I downloaded the EWSEditor project from CodePlex, so I didn't have to create something from the beginning.  

EWSEditor
https://ewseditor.codeplex.com/

It has a form for file attachments, and shows you how to save to file.

        private void MnuSaveAttach_Click(object sender, EventArgs e)
        {
            // Don't do anything if a content row is not selected
            if (this.ContentsGrid.SelectedRows.Count == 0)
            {
                return;
            }

            Attachment attach = this.ContentsGrid.SelectedRows[0].Cells[ColNameAttachmentObj].Value as Attachment;

            // If we can't get the attachment object bail out
            if (attach == null)
            {
                return;
            }

            // Get the file name we'll save to and bail out if we don't succeed
            string fileName = this.GetTargetFileName();
            if (fileName == string.Empty)
            {
                return;
            }

            // If the attachment is a FileAttachment then simply save the content
            FileAttachment fileAttach = attach as FileAttachment;
            if (fileAttach != null)
            {
                if (fileAttach.Content == null)
                {
                    ErrorDialog.ShowWarning("Cannot save FileAttachment because FileAttachment.Content is NULL.");
                    return;
                }

                try
                {
                    this.Cursor = Cursors.WaitCursor;

                    System.IO.File.WriteAllBytes(fileName, fileAttach.Content);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
            else
            {
                ItemAttachment itemAttachment = attach as ItemAttachment;
                if (itemAttachment != null)
                {
                    if (itemAttachment.Item == null)
                    {
                        ErrorDialog.ShowWarning("Cannot save ItemAttachment because ItemAttachment.Item is NULL.");
                        return;
                    }

                    try
                    {
                        this.Cursor = Cursors.WaitCursor;

                        EWSEditor.Common.DumpHelper.DumpXML(
                            itemAttachment.Item,
                            fileName);
                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;
                    }
                }
            }
        }

Open in new window

0
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

Lynchie435Author Commented:
Hi Bob,

I struggle to understand C# and I know that the converters aren't always reliable.

Where did you find that code using the EWSEditor?

Sorry for my late reply, - have been on holiday.

Cheers,

J
0
Bob LearnedCommented:
Look at the Forms\AttachmentsContentForm file.
0
Bob LearnedCommented:
VB.NET:

Private Sub MnuSaveAttach_Click(sender As Object, e As EventArgs) Handles MnuSaveAttach.Click
	' Don't do anything if a content row is not selected
	If Me.ContentsGrid.SelectedRows.Count = 0 Then
		Return
	End If

	Dim attach As Attachment = TryCast(Me.ContentsGrid.SelectedRows(0).Cells(ColNameAttachmentObj).Value, Attachment)

	' If we can't get the attachment object bail out
	If attach Is Nothing Then
		Return
	End If

	' Get the file name we'll save to and bail out if we don't succeed
	Dim fileName As String = Me.GetTargetFileName()
	If fileName = String.Empty Then
		Return
	End If

	' If the attachment is a FileAttachment then simply save the content
	Dim fileAttach As FileAttachment = TryCast(attach, FileAttachment)
	If fileAttach IsNot Nothing Then
		If fileAttach.Content Is Nothing Then
			ErrorDialog.ShowWarning("Cannot save FileAttachment because FileAttachment.Content is NULL.")
			Return
		End If

		Try
			Me.Cursor = Cursors.WaitCursor

			System.IO.File.WriteAllBytes(fileName, fileAttach.Content)
		Finally
			Me.Cursor = Cursors.[Default]
		End Try
	Else
		Dim itemAttachment As ItemAttachment = TryCast(attach, ItemAttachment)
		If itemAttachment IsNot Nothing Then
			If itemAttachment.Item Is Nothing Then
				ErrorDialog.ShowWarning("Cannot save ItemAttachment because ItemAttachment.Item is NULL.")
				Return
			End If

			Try
				Me.Cursor = Cursors.WaitCursor

				EWSEditor.Common.DumpHelper.DumpXML(itemAttachment.Item, fileName)
			Finally
				Me.Cursor = Cursors.[Default]
			End Try
		End If
	End If
End Sub

Open in new window

0
Lynchie435Author Commented:
Cheers Bob,

I have finally got something working!

' Bind to an existing message item, requesting its Id property plus its attachments collection.
                    Dim message As EmailMessage = EmailMessage.Bind(exch, New ItemId(DirectCast(i, EmailMessage).Id.ToString), New PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments))

                    ' Iterate through the attachments collection and load each attachment.
                    For Each attachment As Microsoft.Exchange.WebServices.Data.Attachment In message.Attachments
                        If TypeOf attachment Is FileAttachment Then
                            Dim fileAttachment As FileAttachment = TryCast(attachment, FileAttachment)

                            ' Load the file attachment into memory and print out its file name.
                            fileAttachment.Load()
                            Console.WriteLine("Attachment name: " + fileAttachment.Name)

                            ' Load attachment contents into a file.
                            fileAttachment.Load("C:\temp\" + fileAttachment.Name)

                            ' Stream attachment contents into a file.
                            Dim theStream As New FileStream("C:\temp\Stream_" + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite)
                            fileAttachment.Load(theStream)
                            theStream.Close()
                            theStream.Dispose()
                        Else
                            ' Attachment is an item attachment.
                            ' Load attachment into memory and write out the subject.
                            Dim itemAttachment As ItemAttachment = TryCast(attachment, ItemAttachment)
                            itemAttachment.Load()
                            Console.WriteLine("Subject: " + itemAttachment.Item.Subject)
                        End If
                    Next

Open in new window


Code is above - thank you for your persistence in helping me :)

J
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Lynchie435Author Commented:
Bob's persistence put me on the right track - thanks so much!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Exchange

From novice to tech pro — start learning today.