The problem of optimal energy harvesting for a piezoelectric element driven by mechanical vibrations is stated in terms of an ODE system with hysteresis under the time derivative coupling a mechanical oscillator with an electric circuit with or without inductance. In the piezoelectric constitutive law, both the self-similar piezoelectric butterfly character of the hysteresis curves and feedback effects are taken into account in a thermodynamically consistent way. The physical parameters of the harvester are chosen to be the control variable, and the goal is to maximize the harvested energy for a given mechanical load and a given time interval. If hysteresis is modeled by the Preisach operator, the system is shown to be well-posed with continuous data dependence. For the special case of the play operator, we derive first-order necessary optimality conditions and an explicit form of the gradient of the total harvested energy functional in terms of solutions to the adjoint system.