Refactor message sending code