Why, in particular is this a CGI script?
The way I'd do it, if I had to script to send that many messages, and only had a web front end to do it from, would be to use the web system to generate the information, and write the information out to a temporary file... then have something else (perhaps in cron?) that checks for the existance of /path/to/that/file.info and starts sending the mail.
Of course, if this is on a box-not-your-own, there are security issues with this... be aware.
IANAPG, YMMV, etc