PHPMailer ultimate tutorial

PHP have inbuilt mail() function to send email right from the code. This is easy to use and effective too but it has one serious problem. It gives load to production server and also provide no guarantee about email delivery.

PHPMailer is one of the popular and easy to use email library for php. This solves the issue of production load and guarantee of email delivery by allowing us to configure SMTP server.

How to use it?

For your ease i have created a custom function which of course uses PHPMailer and SMTP. Here is a function.

    function sendmail($to,$subject,$message,$name)
                  $mail             = new PHPMailer();
                  $body             = $message;
                  $mail->SMTPAuth   = true;
                  $mail->Host       = "";
                  $mail->Port       = 587;
                  $mail->Username   = "[email protected]";
                  $mail->Password   = "your gmail password";
                  $mail->SMTPSecure = 'tls';
                  $mail->SetFrom('[email protected]', 'Your name');
                  $mail->AddReplyTo("[email protected]","Your name");
                  $mail->Subject    = $subject;
                  $mail->AltBody    = "Any message.";
                  $address = $to;
                  $mail->AddAddress($address, $name);
                  if(!$mail->Send()) {
                      return 0;
                  } else {
                        return 1;

To use this you need two files, class.phpmailer.php and class.smtp.php. You can download and copy these two files from link given below.

External link: Download PHPMailer library.

Once download place those two files plus the one contains above function. Here is a link of the file.

Internal link : Download custom phpmailer function.

      $to       =   "some email";
      $subject  =   "Hello";
      $message  =   "hello <i>how are you.</i>";
      $name     =   "Shahid Shaikh";
      $mailsend =   sendmail($to,$subject,$message,$name);
        echo '<h2>email sent.</h2>';
        echo '<h2>There are some issue.</h2>';

Performance study:

Recently i was assigned to one project in my company and in that we were using php mail() function. This function used to take like 30 seconds to send one email. Reason was the heavy production server but obviously this is not what client expects.

So i changed it to PHPMailer and after using the Google app smtp i am able to send email within 3 seconds at top. Reduction of 27 seconds and guaranteed delivery of email.

Further study:


Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126