Send Mail via SMTP using PHPMailer

PHP has several method to send the mail and sending the mail using SMTP settings is one of them.
Before some days I have posted one article which shows how to send the mail using SMTP. In this post I will going to explain Send Mail using PHPMailer with SMTP settings.

Earlier post was about send mail using SMTP with PEAR::Mail package.

Let’s see how you can send mail using SMPT with PHPMailer:

# Include PHP Mailer Class require_once("class.phpmailer.php"); # Create object of PHPMailer $mail = new PHPMailer(); // Inform class to use SMTP $mail->IsSMTP(); // Enable this for Testing $mail->SMTPDebug = 2; // Enable SMTP Authentication $mail->SMTPAuth = true; // Host of the SMTP Server $mail->Host = "host.smtpserver.com"; // Port of the SMTP Server $mail->Port = 25; // SMTP User Name $mail->Username = "[email protected]"; // SMTP User Password $mail->Password = "user_pass"; // Set From Email Address $mail->SetFrom("[email protected]", "From Name"); // Add Subject $mail->Subject = "PHPMailer SMTP Testing"; // Add the body for mail $body = "This is the mail body"; $mail->MsgHTML($body); // Add To Address $to "[email protected]"; $mail->AddAddress($to, "SMTP Test"); // Finally Send the Mail if(!$mail->Send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent Successfully!"; }
# Include PHP Mailer Class
require_once("class.phpmailer.php");

# Create object of PHPMailer
$mail = new PHPMailer();

// Inform class to use SMTP
$mail->IsSMTP();

// Enable this for Testing
$mail->SMTPDebug  = 2;

// Enable SMTP Authentication
$mail->SMTPAuth   = true;

// Host of the SMTP Server
$mail->Host = "host.smtpserver.com";

// Port of the SMTP Server
$mail->Port = 25;

// SMTP User Name
$mail->Username   = "[email protected]";

// SMTP User Password
$mail->Password = "user_pass";

// Set From Email Address
$mail->SetFrom("[email protected]", "From Name");

// Add Subject
$mail->Subject    = "PHPMailer SMTP Testing";

// Add the body for mail
$body = "This is the mail body";
$mail->MsgHTML($body);

// Add To Address
$to "[email protected]";
$mail->AddAddress($to, "SMTP Test");


// Finally Send the Mail
if(!$mail->Send())
{
  echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
  echo "Message sent Successfully!";
}

As I have used the both PEAR::Mail and PHPMailer, and I found that PHPMailer is very easy to learn and use.

You can download PHPMailer from here.

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: