What version of Moodle are you using? I don't see anything in your code that would cause the problems you are seeing, but I would say that you don't need any of the globals except $DB since you use that directly. You also don't need to include config.php as it's already been done at that point.
It would be interesting to see if running the core send_failed_login_notifications task also causes the same issue because it also uses email_to_user.
Also, how are you testing running the task? It looks like you running the single task from the UI? What happens when you run the single task from the command line using the admin/tool/task/cli/schedule_task.php?