This topic has been in my todo list for 3 months already so it’s time to add another great information to our knowledge base. To provide our mailing functionality, I choose SwiftMailer over Zend_Mail. I have integrated SwiftMailer into our Zend Framework based project and here it goes.
Setup SwiftMailer
First, get SwiftMailer from it’s download page. It is just a few 300K+ tar.gz file. Extract the contents and put it on the library directory of your Zend Framework project directory.
project_dir application public library Zend Swiftmailer {SwiftMailer files here}
The Code
Since SwiftMailer uses different filename conventions, we cannot use Zend Frameworks autoloading feature. Instead, we will use a simple require_once. To use SwiftMailer’s own autoloading feature, include the swift_required.php file.
require_once ‘Swiftmailer/swift_required.php’;
Basically, you will need to setup these three components to get you started:
- Transport
- Mailer
- Message
//create transport $transport = Swift_SmtpTransport::newInstance() ->setHost('smtp.gmail.com') ->setEncryption('tls') ->setPort(465) ->setUsername('your_google_username@gmail.com') ->setPassword('secret_password'); //Create mailer $mailer = Swift_Mailer::newInstance($transport); //Create the message $message = Swift_Message::newInstance() ->setSubject('subject') ->setFrom(array('frommail@gmail.com' => 'The Name of Sender')) ->setTo('send_to@domain.com') ->setBody('The HTML body here', 'text/html'); //Send the message $mailer->send($message);
That’s it! I hope I would memorize that one. Anyway, if ever I forgot, I’ll just visit this page. Pretty cool huh?