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(‘mail.example.com’, 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@example.com’);
$transport->setPassword(‘your_password_here’);

$message = Swift_Message::newInstance();
$message->setSubject(‘Set the subject of the e-mail’);
$message->setFrom(array(‘email@example.com’ => ‘Your Name/Company Name’));
$message->setTo(array($email));
$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

if(!$result)
{
echo ‘failure’;
}
else
{
echo ‘success’;
}

About Ben Stones

Ben's main IT experience is on software, programming, website development and marketing topics including search engine optimisation. At eUKhost, he regularly works alongside the marketing department on product marketing strategies, and in the development and quality control of the communications which are sent to customers and through the press distribution network. Aside from his regular collaboration with the marketing department on product marketing objectives, Ben occasionally works with the design department in conjunction with the management team on the development of new product pages and the stringent quality control requirements.
This entry was posted in Industry Knowledge Hub, Other Hosting Services and Related, Tutorials, Web Hosting Articles and tagged , , , , , . Bookmark the permalink.

Leave a Reply