C.J. Chivers' book "The Gun" (a really good read, by the way, though it's mostly about the AK-47) contains an in-depth analysis of M16's failure in Vietnam. His conclusion is that it was a combination of factors relating to the gun's design, Colt's cost cutting efforts, the Ordnance Corp's negligence, and politics. The U.S. Military did not have an answer to the AK-47 early in the war, so they expedited the adoption of the M16 without conducting proper R&D. The M16 was still a prototype weapon when it went into production.
The original guns that were sent to Vietnam had major corrosion issues because Colt didn't bother to chrome plate the barrel and chamber (Colt claimed that the steel alloy used in the M16 barrel was corrosion resistant and chrome plating was not necessary, which was proven to be false). Aluminium receivers were likewise corroding because Colt used low-quality anodizing. The other major problem was the change from extruded powder to ball propellant by the Ordnance Department. The new powder increased fouling and gas port pressures, greatly reducing reliability. Yet, Colt, with the knowledge and tacit approval of the Ordnance Corps, test fired guns with the old-style propellant to make them pass quality control. Then there were Colt's wildly exaggerated claims and doctored filed reports about the lethality of the 5.56mm round (i.e. ripping of arms and legs) that sound comical now but were actually one of the main reasons behind M16's adoption. But that's a different story.