Exporting users from DBMail to Postfix lookup table

I wrote so many scripts the last couple of years that I can’t remember anymore… anyways, I was working on my mail server config today and found this little PHP script that exports users from the DBMail database to a Postfix lookup table, so that unknown users can be rejected upfront by postfix (thus reducing the load on the mail server). It also outputs a list of domains.

$mysqli = new mysqli("localhost", "dbmail", "yourpassword", "dbmail");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
$q = $mysqli->query("SELECT DISTINCT alias FROM dbmail_aliases");
$content = '';
$domains = array();
while($r=$q->fetch_assoc()) {
$content .= $r['alias']." OK\n";
$parts = explode('@', $r['alias']);
if(!in_array($parts[1], $domains)) {
$domains[] = $parts[1];
file_put_contents('myusers', $content);
file_put_contents('mydomains', join("\n", $domains));
exec('postmap myusers');

Maybe it is of some use for anybody out there… the config in /etc/postfix/main.cf should look like:

mydestination = /etc/postfix/mydomains localhost
local_recipient_maps = hash:/etc/postfix/myusers $alias_maps