Refactored Javascript code for mass emailing