Tag Archives: email

If you had used Symfony 1.2 with Swift 3 before, you probably sent emails like this:

try
{
  $mailer = new Swift(new Swift_Connection_NativeMail());
  $message = new Swift_Message('The subject', 'The body html', 'text/html');
  $mailer->send($message, 'to@user.com', 'noreply@company.com');
  $mailer->disconnect();
}
catch (Exception $e)
{
  $mailer->disconnect();
}

However, due to API changes in Swift 4, that would have thrown an error:

Fatal error: Cannot instantiate abstract class Swift in /[...]/apps/frontend/modules/[...]/actions/actions.class.php on line 40

It turns out that now the class Swift is defined as abstract, which means it can’t be instantiated. Now, classes that you used to instantiate directly, like Swift_Message, have been added factory methods called newInstance

require_once('lib/vendor/swift/swift_init.php'); # needed due to symfony autoloader
$mailer = Swift_Mailer::newInstance(Swift_MailTransport::newInstance());
$message = Swift_Message::newInstance('The subject')
         ->setFrom(array('noreply@company.com' => 'Mailer Name'))
         ->setTo(array('email@email.com' => 'Name Lastname'))
         ->setBody('The body html', 'text/html');
$mailer->send($message);

Remember that it’s good practise to get the body HTML from a partial, instead of hardcoding it into the action.

$mailBody = $this->getPartial('emailPartial', array(/* parameters */));
// ...
->setBody($mailBody, 'text/html');

The code has become a lot more readable, easier to customize and write.
More information here and here.