Wednesday, February 8, 2012

Sending Transactional Emails from a PHP Script

It's easy to send SMTP emails using PHP and JangoSMTP. Just upload the Swift Mailer library to your server, then set up an SMTP email using swift.

This example demonstrates how to set up and send an email from a PHP script using JangoSMTP. Download the source code for this example, insert your own JangoSMTP username/password/etc and you're ready to rock!

// include the Swift Mailer code
include_once "Swift/lib/swift_required.php";
 
// Set up the plain text body of the email
$text = "A plain text message sent from a PHP script!\n";
// set up the HTML portion of the email
$html = <<<EOM
<html>
  <head></head>
  <body>
    <p>This is an HTML message sent from a PHP script!
    </p>
  </body>
</html>
EOM;
 
// set the from address
// this must be an address stored in your JangoSMTP settings
$from = array('YourEmail@YourDomain.com' => 'Your Name');
// add recipients
$to = array(
  'ToAddress@Domain.com'=>'Recipient Name'
);
// set the subject of the email
$subject = 'JangoSMTP Transactional Email from PHP';
 
// your JangoSMTP login credentials
$username = 'Your JangoSMTP Username';
$password = 'Your JangoSMTP Password';
 
// setup Swift mailer parameters
$transport = 
    Swift_SmtpTransport::newInstance('relay.jangosmtp.net', 25);
$transport->setUsername($username);
$transport->setPassword($password);
$swift = Swift_Mailer::newInstance($transport);
 
// set up the email message in swift
$message = new Swift_Message($subject);
// set the body of the email
$message->setFrom($from);
$message->setBody($html, 'text/html');
$message->setTo($to);
$message->addPart($text, 'text/plain');
 
// send the message through jangosmtp
if ($recipients = $swift->send($message, $failures))
{
 // inform the user if sending succeeds
 echo 'Email sent to '.$recipients.' users';
}