How do I use PHPMailer? I can't find a simple decent tutorial online

Michael Waterfall picture Michael Waterfall · Aug 23, 2009 · Viewed 25.9k times · Source

I'm trying to send out a Plain/HTML multipart email out and I'm currently using PHP's mail() function. Many people have recommended PHPMailer so I thought I'd give it a go.

However, as everything seems to be nowadays, it appears very complicated. I downloaded it and it talks about installing it and configuring MySQL connections and SMTP connections!? All I want to do is use a nice class that will build the MIME emails for me and send them! I understand the SMTP possibilities but it all seems so complex!

Is there some way of simply just using it, for example, include a php file (no server installation or re-compiling PHP!) and then just using the class to build and send the email?

I'd be very grateful if someone could explain things simply! I'm sure it's possible and I can't believe after my hours of searching there's no really good, simple article about it online. Everything's TOO complicated when I know it doesn't need to be!

Answer

karim79 picture karim79 · Aug 23, 2009

Pretty way (from this link), first extend PHPMailer and set the defaults for your site :

require("class.phpmailer.php");

class my_phpmailer extends phpmailer {
    // Set default variables for all new objects
    var $From     = "[email protected]";
    var $FromName = "Mailer";
    var $Host     = "smtp1.example.com;smtp2.example.com";
    var $Mailer   = "smtp";                         // Alternative to IsSMTP()
    var $WordWrap = 75;

    // Replace the default error_handler
    function error_handler($msg) {
        print("My Site Error");
        print("Description:");
        printf("%s", $msg);
        exit;
    }

    // Create an additional function
    function do_something($something) {
        // Place your new code here
    }
}

Then include the above script where needed (in this example it is named mail.inc.php) and use your newly created my_phpmailer class somewhere on your site:

require("mail.inc.php");//or the name of the first script

// Instantiate your new class
$mail = new my_phpmailer;

// Now you only need to add the necessary stuff
$mail->AddAddress("[email protected]", "Josh Adams");
$mail->Subject = "Here is the subject";
$mail->Body    = "This is the message body";
$mail->AddAttachment("c:/temp/11-10-00.zip", "new_name.zip");  // optional name

if(!$mail->Send())
{
   echo "There was an error sending the message";
   exit;
}

echo "Message was sent successfully";