The issue is probably the max_execution_time set in the php.ini file on the server... the default is 30 seconds. Line 47 is supposed to set the timeout to infinite, but that is disabled on some shared servers. You could talk to your hosting provider to see if you can update the script time limit somehow.
Sometimes you need a dedicated server to remove script timeout limits and email limits.
Another solution is to send the email in batches and use a CRON that runs intermittently to send them automatically when queued.
To do that you would have to create an email queue table and use a multiple insert to record all of the emails to be sent. Then the php page that is initiated from the CRON could get the next 50 messages, and send the emails, deleting the rows as they are sent. That way if it didn't finish it would just start over where it left off until all of the emails are sent.