Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2014-11-11
8
Medium Priority
?
1,643 Views
Last Modified: 2014-12-01
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
0
Comment
Question by:Lynchie435
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
8 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 40438075
First of all, which version of EWS are you using?
0
 

Author Comment

by:Lynchie435
ID: 40440399
Hi Bob,

I am using EWS 2.2.

Regards,

James
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 40452270
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
Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

 

Author Comment

by:Lynchie435
ID: 40461662
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
 
LVL 96

Expert Comment

by:Bob Learned
ID: 40462301
Look at the Forms\AttachmentsContentForm file.
0
 
LVL 96

Assisted Solution

by:Bob Learned
Bob Learned earned 2000 total points
ID: 40462309
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
 

Accepted Solution

by:
Lynchie435 earned 0 total points
ID: 40466511
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
 

Author Closing Comment

by:Lynchie435
ID: 40473312
Bob's persistence put me on the right track - thanks so much!
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unified and professional email signatures help maintain a consistent company brand image to the outside world. This article shows how to create an email signature in Exchange Server 2010 using a transport rule and how to overcome native limitations …
Check out this step-by-step guide for using the newly updated Experts Exchange mobile app—released on May 30.
how to add IIS SMTP to handle application/Scanner relays into office 365.
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Suggested Courses

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question