refactor mail function