send mail if error occured, and refactor.