When I had my 2007 M35, a local tint shop broke (smashed) my key fob. They, of course, admitted fault and paid for replacement. The locksmith they contracted with had a huge assortment of key fobs in stock and was charged with providing me a replacement. I took that locksmith 3 key fobs (each was verified to be THE proper key), a team of 2 technicians, two different laptop gizmos, and 3 trips to his shop to get my replacement key fob to work properly. They told me the 2006-2007 M's are among the hardest to properly program.
As Ilya said, it's best to have the dealer do it. Long as you can find a key fob with matching numbers, you can buy it yourself and save some cash. But there is little hope of avoiding the exorbitant cost for the dealer to program it.