How to send mail using SMTP in PHP

How to send mail using SMTP in PHP

SwiftMailer Logo

You have two primary choices that you can use: SwiftMailer library or the PHP Extension and Application Repository (PEAR). To use SwiftMailer, here is an example (although their documentation describes in more detail the individual methods, etc.)

$transport = Swift_SmtpTransport::newInstance(‘’, 587); // your mail server address and port. If you don’t know what yours is, go to cPanel -> E-mail Settings and for the specific e-mail account, More -> Configure E-mail Client – it will be displayed there.

$mailer = Swift_Mailer::newInstance($transport); // creates new instance of an SMTP transport specifically

$transport->setUsername(’[email protected]’);

$message = Swift_Message::newInstance();
$message->setSubject(‘Set the subject of the e-mail’);
$message->setFrom(array(’[email protected]’ => ‘Your Name/Company Name’));
$message->addPart(‘<p>If you want <b>HTML in your e-mail use addPart()</b></p>’, ‘text/html’);

$result = $mailer->send($message); // returns FALSE boolean on failure

echo ‘failure’;
echo ‘success’;

Ben Stones


Leave your comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.