Efficient alternatives in energy production and consumption are constantly being investigated and conducted by increasingly strict policies. Buildings have a significant influence on electricity consumption, and their management may contribute to the sustainability of the electricity sector. Additionally, with growing incentives in the distributed generation (DG) and electric vehicle (EV) industries, it is believed that smart buildings (SBs) can play a key role in sustainability goals. In this work, an energy management system is developed to reduce the power demands of a residential building, considering the flexibility of the contracted power of each apartment. In order to balance the demand and supply, the electrical power provided by the external grid is supplemented by microgrids such as battery energy storage systems (BESS), EVs, and photovoltaic (PV) generation panels. Here, a mixed binary linear programming formulation (MBLP) is proposed to optimize the scheduling of the EVs charge and discharge processes and also those of BESS, in which the binary decision variables represent the charging and discharging of EVs/BESS in each period. In order to show the efficiency of the model, a case study involving three scenarios and an economic analysis are considered. The results point to a 65% reduction in peak load consumption supplied by an external power grid and a 28.4% reduction in electricity consumption costs.