United Parcel Service will forfeit to the government $40 million that it collected from pharmacies over seven years for delivering drugs that were illegally purchased online without a prescription, federal prosecutors in San Francisco said Friday.

The agreement allows the company to avoid prosecution. In a joint statement, UPS acknowledged it had been on notice that some of the pharmacies were violating the law, but did not close their accounts.