First suggestion would be to put more info in your error message:
rename $tempfile, "tempdir/".$new_filename
or die "Cannot rename $tempfile to tempdir/$new_filename" $!";
You are renaming an open file. This is indeed allowed, but in this code, I see no need and would avoid that.
while ( <$attach> ) makes no sense because $attach is a text string - what you are trying to do is not at all clear.
Update: Also add use strict; use warnings to your code. If you had done that you will see that while ( <$attach> ) produces the error of attempted read on an unopened file handle.