Delete TEMP files when sending mails with attached files

Attaching Documents is a frequently used functionality in Ax (PDF is just an example, but it is true for any attached file):

image

That is why tmp-files, that are generated each time you are using this, might consume quickly an important part of your hard disk, since they are not deleted at the end of the process. The temp-files are copies of the generated text, pdf or RTF files from the tmp-directory. This directory is defined as an user environment variable:

image 

image

The easiest way is to schedule a batch which is cleaning the temp directly each time you are starting or shutting down your system. But even this is sometimes not enough. The it is necessary to change the X++ code.

When sending a report as an attachment, the kernel calls the method reportSendMail of the Info-class and passes all necessary information about the attachment in a variable of type PrintJobSettings.

The email is sent in the last line of this method:

 m.sendMailAttach(p1.mailTo(),p1.mailCc(), p1.mailSubject(),'axapta report', true, p1.fileName(), fileName);

“m” is a variable of type SysINetMail. The path and file-name of the temp-file is passed as argument with p1.fileName(). Because the tmp-file is only used to attach the file to mail by using the Mapi, the is no risk to delete the file at the end of this process. The best place to delete this file is after the logoff of the Mapi session in the method sendMailAttach:

 

    1:          this.logoff();
    2:          if (!isRunningOnServer())
    3:          {
    4:              if(WinAPI::fileExists(_attachPath))
    5:              {
    6:                  WinAPI::deleteFile(_attachPath);
    7:              }
    8:          }

Line 2 to 8 is the new code. Line 2 checks if the code is called from the AOS, which is always false, but to be sure that any other custom-code will work, it is better to check this nevertheless. It would be better to encapsulate the delete-call in a try-catch-block, because deleting files is always a risk and must be treated, but this is just an example of course.