Corion's analysis was bang-on (yes, this really is horrible code.) One more suggestion - take this script, and rewrite it using Template Toolkit to generate the content and MIME::Lite to manage the email. You'd probably cut the script to a third the length it is now, and you'd be amazed how much more readable and maintainable it would be.
Just my $0.02,
Those who know that they are profound strive for clarity. Those who
would like to seem profound to the crowd strive for obscurity.