Increasing the share of Electric Vehicles (EVs) powered by renewable-based Distributed Energy Resources (DERs) is a key step towards climate neutrality. However, increasing the penetration of EVs and Photovoltaic (PV) generators may create large and hardly predictable fluctuations in power supply and demand, thus destabilising the grid. In this paper, an optimisation algorithm for smart EV charging is proposed to reduce the overall net-load variance through a more efficient exploitation of the available PV power, EV charging shifting, or vehicle-to-grid (V2G). Key distinctive features of the proposed approach are: (i) the formulation as a quadratic programming problem; (ii) the capability to enable a V2G charging policy, (iii) the inclusion of specific constraints regarding EVs' availability, owners' charging requirements and, partially, voltage stability; (iii) the study of the combined impact of EV and PV penetration on bus voltages, line currents, district self-sufficiency, and EV battery lifetime. The proposed approach is tested not only in ideal conditions, but also considering a basic persistence forecasting model of load and PV generation over subsequent days. The results of grid-level simulations in a case study show that the proposed approach could decrease the net-load variance by up to 60% if no forecasting errors occur and by about 50% when the persistence forecasting model is used. Additionally, the V2G policy notably decreases both the range of voltage fluctuations and the risk of line overloading, although at the expense of EVs' battery lifetime, whose reduction actually depends on the battery capacity.& COPY; 2023 The Authors. Published by Elsevier Ltd. This is an open access article under the CC BY-NC-ND license (http://creativecommons.org/licenses/by-nc-nd/4.0/).