Using the Decorator Plugin
To use the Decorator plugin, simply create an associative array of replacements based on email addresses and then use the mailer's registerPlugin() method to add the plugin.
First create an associative array of replacements based on the email addresses you'll be sending the message to.
$replacements = array();
foreach ($users as $user) {
$replacements[$user['email']] = array(
'{username}'=>$user['username'],
'{password}'=>$user['password']
);
}
Now create an instance of the Decorator plugin using this array of replacements and then register it with the Mailer. Do this only once!
$decorator = new Swift_Plugins_DecoratorPlugin($replacements); $mailer->registerPlugin($decorator);
When you create your message, replace elements in the body (and/or the subject line) with your placeholders.
$message = Swift_Message::newInstance()
->setSubject('Important notice for {username}')
->setBody(
"Hello {username}, we have reset your password to {password}\n" .
"Please log in and change it at your earliest convenience."
)
;
foreach ($users as $user) {
$message->addTo($user['email']);
}
When you send this message to each of your recipients listed in your $replacements array they will receive a message customized for just themselves. For example, the message used above when received may appear like this to one user:
Subject: Important notice for smilingsunshine2009 Hello smilingsunshine2009, we have reset your password to rainyDays Please log in and change it at your earliest convenience.
While another use may receive the message as:
Subject: Important notice for billy-bo-bob Hello billy-bo-bob, we have reset your password to dancingOctopus Please log in and change it at your earliest convenience.
While the decorator plugin provides a means to solve this problem, there are various ways you could tackle this problem without the need for a plugin. We're trying to come up with a better way ourselves and while we have several (obvious) ideas we don't quite have the perfect solution to go ahead and implement it. Watch this space.