PHP Send Email Via PHPMailer Example

How to send email using PHPMailer

PHP Send Email Via PHPMailerFor those of you who want to send email via PHPMailer instead of the mail() command, here is a simple script I wrote to facilitate sending email. Because there are so many different areas within a site that can send email messages automatically I have externalized the script and include it when needed.

The script includes logic to monitor for an error from PHPMailer and if found send the email using mail() and send an email to the administrator that PHPMailer failed.

This function accepts an optional file parameter. If the file parameter is passed it will be included in the email as an attachment.

For this site I downloaded and installed PHPMailer from GitHub here. There are other options available for loading the PHPMailer classes. Select what works best for you.

The mail script (named includes/sendEmail.php):

 
<?php

// send email via phpmailer

function sendEmail($mailFrom, $mailFromName, $mailTo, $mailToName, $mailSubject, $mailBody, $file="") 
{ 
    require_once("/path/to/PHPMailer/PHPMailerAutoload.php");

// initialize mailer
    $email = new PHPMailer();

//    $email->SMTPDebug = 3;				//Enable SMTP debugging. 
    $email->isSMTP();					//Set PHPMailer to use SMTP.
    $email->Host = "host.yourdomain.com";		//Set SMTP host name
    $email->SMTPAuth = true;				//Set this to true if SMTP host requires authentication to send email
    $email->Username = "somone@yourdomain.com";		//username
    $email->Password = "password";			//password (You should protect this)
    $email->SMTPSecure = "tls";				//If SMTP requires TLS encryption then set it
    $email->Port = 587;					//Set TCP port to connect to 
    $email->isHTML(true);

    $email->From      = $mailFrom;
    $email->FromName  = $mailFromName;
    $email->Subject   = $mailSubject;
    $email->Body      = $mailBody;
    $email->AddAddress($mailTo, $mailToName);

// optional attachment - if passed in
    if ($file != "")
    {
        $filename = basename($file);
        $file_to_attach = $file;
        $email->AddAttachment($file_to_attach, $filename);
    }

// send - check for errors and send via mail() if needed
    if(!$email->send()) 
    {
        // if phpmailer fails - send the email old school with mail()
        $sent = sendEmailViaMailCommand($mailFrom, $mailFromName, $mailTo, $mailToName, $mailSubject, $mailBody) ;

        // notify staff of error - error values
        $errorFrom = $mailFrom;
        $errorFromName = $mailFromName;
        $errorTo = $mailTo;
        $errorToName = $mailToName;
        $errorSubject = $mailSubject;
        $errorBody = $mailBody;

        $mailFrom = "someone@yourdomain.com";
        $mailFromName = "Administrator";
        $mailTo = "someone@yourdomain.com";
        $mailToName = "Administrator";
        $mailSubject = "PHPMailer SMTP error";
        $mailBody = "The system emailer failed - possible password mismatch.";
        $mailBody .= "<p>Error message: " . $email->ErrorInfo . "</p>";
        $mailBody .= "<p>Sent via mail() command instead.</p>";
        $mailBody .= "<p>Original Content</p>";
        $mailBody .= "<table>";
        $mailBody .= "    <tr><td>From Email:</td><td>$errorFrom</td></tr>";
        $mailBody .= "    <tr><td>From Name:</td><td>$errorFromName</td></tr>";
        $mailBody .= "    <tr><td>To Email:</td><td>$errorTo</td></tr>";
        $mailBody .= "    <tr><td>To Name:</td><td>$errorToName</td></tr>";
        $mailBody .= "    <tr><td>Subject:</td><td>$errorSubject</td></tr>";
        $mailBody .= "    <tr><td>Body:</td><td>$errorBody</td></tr>";
        $mailBody .= "</table>";
        
        sendEmailViaMailCommand($mailFrom, $mailFromName, $mailTo, $mailToName, $mailSubject, $mailBody);

        return $sent;
    } else { 
        return true;
    }
} 

function sendEmailViaMailCommand($mailFrom, $mailFromName, $mailTo, $mailToName, $mailSubject, $mailBody) 
{ 
    $headers = "From: " . $mailFrom . "\r\n";
    $headers .= "Reply-to: " . $mailFrom . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    $sent = mail($mailTo, $mailSubject, $mailBody, $headers);
    return $sent;
} 

?>

Copy Code

Now a bit of php from another page to use the script:

<?php

	include_once("/includes/sendEmail.php");

        $mailFrom = "someone@yourdomain.com";
        $mailFromName = "Administrator";
        $mailTo = "someoneelse@anotherdomain.com";
        $mailToName = "Someone Else";
	$mailSubject = "The email subject";
	$mailBody = "The email body/content";

	if (!sendEmail($mailFrom, $mailFromName, $mailTo, $mailToName, $mailSubject, $mailBody, $file=""))
	{
		// do something if the mail fails
	}

?>

Copy Code

References

PHPMailer
PHP Include
PHP if
PHP Mail

Leave a Reply

I appreciate and welcome your comments. Please keep in mind that comments are moderated according to my comment policy.
Your email address will not be published. Required fields are marked *