We calculate the leptonic decay constants of heavy-light pseudoscalar mesons with charm and bottom quarks in lattice quantum chromodynamics on four-flavor QCD gauge-field configurations with dynamical u, d, s, and c quarks. We analyze over twenty isospin-symmetric ensembles with six lattice spacings down to a≈0.03 fm and several values of the light-quark mass down to the physical value 12(mu+md). We employ the highly-improved staggered-quark (HISQ) action for the sea and valence quarks; on the finest lattice spacings, discretization errors are sufficiently small that we can calculate the B-meson decay constants with the HISQ action for the first time directly at the physical b-quark mass. We obtain the most precise determinations to-date of the D- and B-meson decay constants and their ratios, fD+=212.7(0.6) MeV, fDs=249.9(0.4) MeV, fDs/fD+=1.1749(16), fB+=189.4(1.4) MeV, fBs=230.7(1.3) MeV, fBs/fB+=1.2180(47), where the errors include statistical and all systematic uncertainties. Our results for the B-meson decay constants are three times more precise than the previous best lattice-QCD calculations, and bring the QCD errors in the standard model predictions for the rare leptonic decays B¯(Bs→μ+μ-)=3.64(11)×10-9, B¯(B0→μ+μ-)=1.00(3)×10-11, and B¯(B0→μ+μ-)/B¯(Bs→μ+μ-)=0.00264(8) to well below other sources of uncertainty. As a byproduct of our analysis, we also update our previously published results for the light-quark-mass ratios and the scale-setting quantities fp4s, Mp4s, and Rp4s. We obtain the most precise lattice-QCD determination to date of the ratio fK+/fπ+=1.1950( -23+16) MeV.