Mark O'Reilly · Nov 10, 2020

How to rename an attachment on an email


I have noticed a problem in some new code I did on one of our productions. I think it is leading to 2 problems. 

I have a file, lets call it 1111111111_2300.pdf. 

We make the file UNIQUE to avoid an issue. This filename in the working directory gets a session ID Added to it before the .pdf. So lets say it was session ID 9 it would be 1111111111_2300#SID9.pdf in a working directory . 

There are further operations to be done on this document before it is sent. For various errors an email is sent back to service users. 

Now as part of being really clear that this document was the one that was sent, the attachment should be called 1111111111_2300.pdf. 

how best can i attach the file 1111111111_2300#SID9.pdf to display names in the email as 1111111111_2300.pdf
Set tSC = msg.AttachFile($P(fileToAttach,"\",1,*-1),$P(fileToAttach,"\",*))

The code I have currently is incorrect. It calls this 

Set newFile = $P(file,"#SID")_".pdf"
If ##class(%File).CopyFile(file,newFile,1)

The problem being

  • existing code only deletes the file after a rejection not newFile
  • Sometimes to attach the file it in somehow isn't finding the file to attach. Now I think this is because windows may be funny in the process of trying to rename the file again just for attaching to an email 

There must be a simplier way to do what our requirement is? 

0 120
Discussion (3)1
Log in or sign up to continue

Use AttachStream method and specify any filename you want.


Thank you so much. I'm pretty much a complete beginner so just saying AttachStream took the full hour or so of trying to figure out how to implement it, so good learning exercise

Can you please check that this is the correct implementation? It works but I am aware I may have missed something that was obvious to it otherwise. I will mark as answer if it is correct. the variable file is the link to the attached file  

Set tStream = ##class(%Stream.FileBinary).%New()
Set tStream.Filename = file
Set tSC = msg.AttachStream(tStream,##class(%File).GetFilename(pRequest.InputData.OriginalFilename))
If $$$ISERR(tSC) {....