Finally, it was time to start debugging thins on my own! That pesky Exchange team is no good! They can't even handle fixing their Exchange servers! And so I did – with one slight difference – this time, instead of testing using my local account, I've opened a PowerShell window using the MSA account used to run the script. I run the same testing script that I used on my standard Active Directory account, and suddenly instead of 1-5 seconds per email, it takes 40-60 seconds, and an error message is thrown that a temp name can't be generated. That's weird. Then it hits me – I go to the temp folder, type “dir” and see hundreds of thousands of 0-byte files called tmpXXXX.tmp going and going and going, and never finishing. GetTempFileName() returns a temporary file name and creates it on a disk. That means every time you run it, it checks if the file exists, and if it does, it generates a new name and again creates it on the temp folder.
That means for every email I sent or prepared for sending but wouldn't it would create an empty file. It was even worse because email body generation actually used [System.IO.Path]::GetTempFileName().Replace(“.tmp,” “.html”) a different name, so the TMP file would never be used, and even the HTML extension was never used because it was all done in memory, so it was doing it unnecessarily. You may be thinking – but why was it taking so long to generate that name?
So why was it taking so long? Whenever I created an email, my script would generate a temp file (instead of a temp string) that led to 1000-10000 temp files created per day, each adding a problem for GetTempFileName() to make next. After running for months without cleaning the temp folder, one of two things happened – I've reached the limit where the GetTempFileName() method would try and generate a unique file name that doesn't exist. It hit 1.8 million files (trying to find a unique one every time), and it stopped, or it has a hardcoded timeout of 1 minute (more likely). Either way – I didn't want to investigate it anymore, as I felt that I'd already achieved the top idiot award for today. The delete command took about 10 minutes to delete all the temp files. And what do you know? Once deleted, the emails started flying in 1 second again.