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(‘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 protected]’);
$transport->setPassword(‘your_password_here’);

$message = Swift_Message::newInstance();
$message->setSubject(‘Set the subject of the e-mail’);
$message->setFrom(array(’[email protected]’ => ‘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’;
}

Ben Stones

Sharing

Leave your comment

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