extract template generation logic for email