Examples: Sending Emails in the Background

Quite often you’ll want to email a user something based on an action they’ve taken on your site. Signed up for a newletter, requested a download link, and so on. However, email systems are notorious for being slow and causing page load headaches. Here we demonstrate how you can use Gearman to “background” the email send task.

The Client

<?php

// ... handle form validation, etc
$email = 'joe@hamburger.com';
$subject = "Eat @ Joe's!";
$body = 'They have the best ceaser salad!';
// ... now the good stuff

$client = new GearmanClient();
$client->addServer();
$result = $client->doBackground("send_email", json_encode(array(
// whatever details you gathered from the form
'email' => $email,
'subject' => $subject,
'body' => $body
)));

// continue page request...
// todo
// todo

What’s great about doBackground() is that it returns as soon as the gearman server receives the job – it does not wait for the job to be processed. This means that the user’s browser isn’t spinning while your code does battle with an SMTP server. In fact, you don’t even need to have a worker ready to process the job when you submit it. Try running the client without a worker running. When you do finally start the worker, it will pick up any waiting jobs.

The Worker

<?php

$worker = new GearmanWorker();
$worker->addServer();

$worker->addFunction("send_email", function(GearmanJob $job) {
$workload = json_decode($job->workload());
echo "Sending email: " . print_r($workload,1);
// You would then, of course, actually call this:
//mail($workload->email, $workload->subject, $workload->body);
});

while ($worker->work());
// todo
// todo