Categories
How-To php WebApps

Symfony Has a Swift Plugin for Sending Gmail

It’s easy to send emails using your gmail account with the Swift Plugin.
Here’s some sample code below


$to          = 'somebody@example.com';

$htmlMessage = "OH HAI!";
$textMessage = "*OH HAI!*";

$connection = new Swift_Connection_SMTP(
  sfConfig::get('app_email_smtp_server'),
  sfConfig::get('app_email_smtp_port'), 
  Swift_Connection_SMTP::ENC_SSL
);

$connection->setUsername(sfConfig::get('app_email_username')); # gmail email
$connection->setPassword(sfConfig::get('app_email_password')); # gmail password

$mailer = new Swift($connection);
$message = new Swift_Message("Your subject goes here. OH HAI!");
 
$message->attach(new Swift_Message_Part($htmlMessage, 'text/html'));
$message->attach(new Swift_Message_Part($textMessage, 'text/plain'));
 
// Send,
// try and catch
try {
  if (!$mailer->send($message, $to, sfConfig::get('app_email_username'))) {
    throw new Exception('mailer error');
  }
} catch (Exception $e) {
    sfContext::getInstance()->getLogger()->info(
      "Caught swift send error exception:\n" .  
      $e->getMessage(). " ".
      $e->getFile() . ": Line ".
      $e->getLine() . "\n", $e->getTraceAsString(), "\n"
  );
}
          
$mailer->disconnect();