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

Lynchie435
Lynchie435 used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Top Expert 2008

Commented:
First of all, which version of EWS are you using?

Author

Commented:
Hi Bob,

I am using EWS 2.2.

Regards,

James
Most Valuable Expert 2012
Top Expert 2008

Commented:
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

Should you be charging more for IT Services?

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

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
Most Valuable Expert 2012
Top Expert 2008

Commented:
Look at the Forms\AttachmentsContentForm file.
Most Valuable Expert 2012
Top Expert 2008
Commented:
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

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

Author

Commented:
Bob's persistence put me on the right track - thanks so much!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial