Solved

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

Posted on 2014-11-11
8
1,226 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
  • 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
Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 

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 500 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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Following basic email etiquette rules will help you write a professional email and achieve a good, lasting impression with your contacts.
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…

832 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