Email Delivery Reports using PHP and WHM API's emailtrack_search
Do you need to generate an email delivery report after sending out a newsletter? Or create an email delivery report for a client who complains that their emails are not being delivered? This used to be a tedious, manual process of logging into the WHM panel, filtering the required records in the Mail Delivery Reports module, and then copying, pasting and formatting the data into a spreadsheet, to be presentable to the end-client.
When dealing with 1000s of records, this gets more complicated, because WHM limits the number of records it displays on each query. So, you have to fetch records in smaller batches and then compile them into your spreadsheet.
To ease the suffering, I decided to write a PHP script that connects to the WHM API and automates this process.
This wasn't as simple as I thought it would be. cPanel's Developer Documentation is:
- complicated:
they have 5 different APIs; some work with the other, some don't. They recommend using their latest UAPI, which doesn't have some functions that WHM API 1 has. - incomplete:
I had to learn from trial and error that the emailtrack_search API call fetches only 250 records at a time, even though the documentation says "If you set max_results_by_type parameter to 0, the function returns unlimited results."
Also, the filter field is supposed to match against the name of one of the function's returns, but I found that it doesn't filter with actionunixtime; it does filter with sendunixtime, so that's fine, but undocumented. - erroneous:
The emailtrack_search function that I was primarily dealing with says to use the parameter nosize=1 to return successful delivery attempts. However, this didn't work. I had to use success=1 to fetch successful delivery attempts.
Even with these annoyances, the API itself is very powerful and can do amazing things, when you've got the code right. To this end, I'm releasing my script publicly on GitHub.
My Email Track Report PHP script utilizes the API called "WHM API 1", using an API Token (that you need to generate from your WHM panel). The script breaks up the total duration into smaller batches (of 30 minutes each; you can change this as per your requirement), and then queries the emailtrack_search function of the API with the sender's email and a bunch of API parameters (my code is well-commented with the explanation of each parameter, so head over to GitHub and fork/download the script). Finally, all the requested records are output as a downloadable CSV file, which you can open in Google Sheets or Microsoft Excel, or whatever floats your boat.
I hope this script makes it quicker for you to generate email reports; or acts as a starting point for you to create your own WHM API scripts to automate other tasks.