· Apr 26, 2022

Save attached file to disk from Email


We have a solution with an EnsLib.EMail.InboundAdapter as services that scan a mailbox on incoming mail with attachments.

When a new email arrives, the service sends the request (with a property %Net.MailMessage) to the process. In the process, we try to loop through and retrieve part 2 which we assume is the file.

set Part = pRequest.Mail.Parts.GetAt (2)

We can read out the file name:
Set FileName = Part.FileName

But how, and is it possible, to save the attached file to disk drive?

I do not see any method that supports that in that class.

Or must we use% Net.POP3 to receive and store the file?

Grateful for answers.

Regards Michael

Product version: IRIS 2021.2
Discussion (4)2
Log in or sign up to continue

Depends on how the attachment is stored by the sender. If it's a binary attachment, the file data will be represented as a stream object in Part.BinaryData. If it's text data, Part.TextData. You just need to create a %Stream object and copy Part.BinaryData (or Part.TextData) to it:

Set stream=##class(%Stream.FileBinary).%New()
Set sc=stream.LinkToFile("/path/to/"_Part.FileName)
Do stream.CopyFrom(Part.BinaryData)
Do stream.Flush() // may not be necessary
Do stream.%Save() // ditto, but better safe than sorry ya know?

You can determine the type of data in the Part via the IsBinary boolean property ... 

Thanks Jeffrey for your answer! I looked at a solution earlier with "LinkToFile" but since I do not know where the file is physically located I abandoned that idea. We are connected to a POP account against an MS Exchange server and I do not even know if it is possible to access the file physically.

But we will take a closer look at that possibility.

Otherwise it seems like we must  use %Net.POP3. I otherwise thought that there were advantages to using EnsLib.EMail.InboundAdapter as it has several functions automatically such as scanning for and deleting mail etc.

Regards Michael

The "file" is a bag of bytes embedded in the received email message, and represented in the %Net.MailMessagePart as a stream object (based on your example, Part.BinaryData for a binary attachment). It's up to you to take that stream object and save it as a file somewhere, which is shown by the suggested CopyFrom method and  "/path/to" string in its argument in my response above.