I send all my mail through my Google Apps account, using Google’s SMTP servers. I spent some time setting up Swift Mailer to do this, so I figured I’d show how I did it.
Setting-up Swift Mailer to send mail through Google’s SMTP servers is quite easy once you put all the correct pieces together. Here are the steps:
Step 1: Download SwiftMailer, unzip it, then upload the “lib” folder to your server.
Step 2: Now you can start writing the PHP code. Begin by including the Swift library:
Of course, make sure to insert the correct path.
Step 3: Setup the transport method for sending. This is where you put in your Google account info:
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587,'tls');
You’ll notice that the port is set to 587, and also the encryption method is properly set to TLS.
Step 4: Create the message. This should be straight forward:
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create the message
$message = Swift_Message::newInstance();
// Give the message a subject
$message->setSubject('Subject Goes Here');
// Set the From address with an associative array
$message->setFrom(array('email@example.com' => 'Your Name'));
// Set the To addresses with an associative array
// Give it a body
$message->setBody('The main body of your message','text/html');
Two things to point out here. Firstly, the message content is being set to ‘text/html‘ so that you may include HTML in your message. Also, while I’m showing you how to set the From address, Google will re-write the header to reflect your actual email address and account name. Google does this automatically.
Step 5: Time to send!
// Send the message!
$result = $mailer->send($message);
That’s it! For further information, consult the documentation: http://swiftmailer.org/docs/introduction.html