Just to reiterate points from the question Dom linked in the comment - Why do many songs in major keys use a bVII chord? - there are a couple of general types of reasons why it's wrong to think that a piece that's said to be (say) "in D Major" will only use notes and chords from D Major. One is that even a piece that really is essentially in a major tonality will still sometimes step outside the notes in the major scale in various ways, to 'make things interesting'. The other is that there are lots of basic tonalities in music that aren't (or aren't quite) major or minor - for example, the modes, and blues-influenced tonalities.
The use of blues-influenced tonality (rather than straight major) is one of the more common reasons why you might get a bVII chord turning up. To highlight the difference between 'straight' major and 'blues influenced' major, have a listen to Joe's Garage, by Frank Zappa. That song is major, for the first 4 minutes - and then the tonality suddenly changes to a bluesy scale, but still with a major tonic chord. In this example I don't think they actually play a bVII chord anywhere in this bluesy section, but it would fit right in - listen to the similarity in tonality to Ramble on by Led Zeppelin, for example, which does use a bVII chord. So that's one reason that bVII chord works in blues-influenced songs (even if those songs seem somewhat 'major') - it's rooted on bVII found in the blues scale.
Even without stepping outside the diatonic scale, you might find a C Major chord that's in a song in D Mixolydian that someone's calling 'D major' for some reason (perhaps because it might be notated as if in D major - but then again, it might not!)
Other reasons why a bVII chord can 'work' in major key are:
- Its root (the note a minor seventh from the tonic note of the key) has a much closer harmonic relationship with the tonic note of the key than the major seventh - it corresponds to the 7th harmonic, much earlier in the harmonic series than a harmonic corresponding to the major seventh.
- Its third and fifth are the second and fourth note of the major scale (same as the diminished VII)
- Being major, it creates a consistent harmonic palette with the other major chords in a major key
- As Laurence points out, it can be seen as 'IV of IV' in songs where the major IV features. This can be relevant in the chord progression bVII - IV - I.
In fact from a harmonic relationships / consonance point of view, you could consider that the major chord based on the flat seventh is less quirky than the diminished chord based on the major seventh. However, the diminished chord also has its place as an interesting dissonance that 'wants to' resolve, and from a theoretical point of view to keep the major scale as one of the diatonic 'family' of scales.