Refactored email function