PHP Mailer Setup How To Use

zardiw

Perch
Is the php mailer class already available in PHP, or do I have to download it to my websites? These are all unix sites.
 
Tutorial with MySql Database access.

This uses a main site config file that makes life easier for you. It also uses an 'extender class' that's nice. Full tutorial link, but I've given you all a cheat sheet: http://www.askapache.com/php/phpfreaks-eric-rosebrocks-phpmailer-tutorial.html

Step 1. In this example, I extracted and then uploaded the phpmailer.zip files to www.yoursite.com/PHPMail


Step 2. Make these 2 files (code below) and put them into your website root, i.e. www.yoursite.com/MainSite.php
and www.yoursite.com/MailExtend.inc

The parts you have to change are in blue. If you use the PHPMail folder name, and the file names (MainSite.php and MailExtend.inc) you
won't have to change much.


MainSite.php:

(This uses SMTP and and an email acct logon)
Code:
<?php
 
// Configuration settings for This Site
 
// Email Settings
$site['from_name'] = '[COLOR="Blue"]James Bond[/COLOR]'; // from email name
$site['from_email'] = 'J[COLOR="Blue"][email protected][/COLOR]'; // from email address
 
// Just in case we need to relay to a different server,
// provide an option to use external mail server.
$site['smtp_mode'] = 'enabled'; // enabled or disabled
$site['smtp_host'] = '[COLOR="Blue"]mail.yoursite.com[/COLOR]';
$site['smtp_port'] = '25';
$site['smtp_username'] = '[COLOR="Blue"][email protected][/COLOR]';
$site['smtp_password'] = '[COLOR="Blue"]emailpassword[/COLOR]';
?>


MailExtend.inc:

What this file does is feed your MainSite parameters to the class.phpmailer.php file.

Code:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/PHPMail/class.phpmailer.php');
 
class ZapMailer extends PHPMailer
{
    var $priority = 3;
    var $to_name;
    var $to_email;
    var $From = null;
    var $FromName = null;
    var $Sender = null;

    functspamapMailer()
    {
        global $site;

        // Comes from MainSite.php $site array

        if($site['smtp_mode'] == 'enabled')
        {
            $this->Host = $site['smtp_host'];
            $this->Port = $site['smtp_port'];
            if($site['smtp_username'] != '')
            {
                $this->SMTPAuth = true;
                $this->Username = $site['smtp_username'];
                $this->Password = $site['smtp_password'];
            }
            $this->Mailer = "smtp";
        }
        if(!$this->From)
        {
            $this->From = $site['from_email'];
        }
        if(!$this->FromName)
        {
            $this-> FromName = $site['from_name'];
        }
        if(!$this->Sender)
        {
            $this->Sender = $site['from_email'];
        }
        $this->Priority = $this->priority;
    }
}
?>

And here's the action script from a form I made. The form has a text field where I can type the message I want to email.

Here's the form fwiw:

Code:
<FORM name="EMForm" method="post" action="PHPActionScriptBelow.php">
        <H2 align="center"><B><FONT face="Tahoma, Arial">WaMu Equity Alert</FONT></B></H2>
        <P><B>This message will be sent to all who have a blank IP address.</B></P>
        <P> 
          <TEXTAREA name="FrmText" rows="10" cols="80"></TEXTAREA>
        </P>
        <P>&nbsp;</P>
        <INPUT type="submit" name="Submit" value="Submit">
        <P>&nbsp; </P>
      </FORM>

The action php script goes through the database and picks the ones that get an email:

Code:
<?php

include "[COLOR="Blue"]databaseconnectionparametersForYour site.[/COLOR]php";


// Grab our config settings
require_once($_SERVER['DOCUMENT_ROOT'].'/MainSite.php');
 
// Grab the Mailer class
require_once($_SERVER['DOCUMENT_ROOT'].'/MailExtend.inc');
 
// instantiate the class

$mailer = new ZapMailer();


// This field is from the form. 
// [COLOR="Blue"]You'll have to modify this code for your application[/COLOR]

$PostFrmText = $_POST["FrmText"];
$StripSlash = stripslashes($PostFrmText);

$SendMessage = wordwrap($StripSlash, 70);

// Subject could be posted in form and passed to the script if you want.

$mailer->Subject  = "This is the subject of the Email";  
$mailer->Body     = $SendMessage;
			
$HoldQuery = "SELECT * FROM Holders";
$HoldResult = mysql_query($HoldQuery) or Print "No Such Query";
$HoldRow = mysql_fetch_array($HoldResult);

$SendCount = 0;
$LoopCount = 0;

// This loops through the database and adds each email via BCC to the main email. Then when it gets them all, it 
// sends just one email. I've only got 400 people in this database, so if you have a lot
// of emails, you might want to send them separately, I don't know.

while ($HoldRow) {
	$LoopCount++;

// SMA if something goes wrong. You might want to do this until bugs are gone.

	if ($LoopCount > 500) die("Too many - $LoopCount");
	
	if ($HoldRow["[COLOR="Blue"]SomeField[/COLOR]"] == "[COLOR="Blue"]WantsEmail[/COLOR]") {	

		$SendTo = $HoldRow["[COLOR="Blue"]EmailField[/COLOR]"];
		
                 echo "Sent To: " . $SendTo . "<BR>";

		$mailer->AddBCC("$SendTo");
		$SendCount++;
	}
		  
	$HoldRow = mysql_fetch_array($HoldResult);
	
}

if(!$mailer->Send()) {
    echo "There was a problem sending this mail!";
    }
    else
    {
    echo "Mail sent!";
}

?><P><?php
echo "Number Sent T1: " . $SendCount;

?>
 
Ok, PHPMailer works as a standalone script, but it won't work inside of Joomla for some reason.

I'm using jumli inside the forms to process the PHP scripts that have PHPMailer inside of them......I've messed with the paths to make it direct, but can't get it to work......anybody got any ideas.....do I have to go into the phpmailer class to fix this?.....z

Update...got the email to work, but the from address is [email protected]****here.biz......lol

When I used this: $mailer->AddAddress($PostEM1); instead of $mailer-> To = $PostEM1; , it started mailing. Maybe it's cause there's a space between > and To....

It's not picking up the info from the site config file though....

Update for Joomla. Ok, got it to work, but it wouldn't pick up the site config file, or the include file, so I hard coded it into the PHP script:

$mailer->From = "[email protected]";
$mailer->FromName = "James Bond, or [email protected]";

$mailer->IsSMTP(); // Sets SMTP mode
$mailer->SMTPAuth = true; // Sets it to use authorized mode

$mailer->Host = "mail.yoursite.com";

$mailer->Username = "[email protected]";
$mailer->Password = "Email password for [email protected]";

$mailer->Subject = $EMSubject; // the Subject text was put into $EMSubject first of course
$mailer->Body = $EMMsg; // ditto for the message
$mailer->AddAddress($PostEM1); // $PostEM1 has the email address you're sending to in it.
if(!$mailer->Send()) echo "There was a problem sending this mail!";


..z
 
Here's the code snippet to send a bunch of emails in batches. There's a limit on how many BCC's you can add. Don't know what it is, but this code works...limiting it to 49 at a time. Notice the extra $mailer->send() at the end, that sends the final batch:

Code:
while ($HoldRow) {
	$LoopCount++;

	if ($LoopCount > 500) die("Too many - $LoopCount");
	
	if ($HoldRow["HEMail"] != "") {

		$SendTo = $HoldRow["HEMail"];
		echo "Sent To: " . $SendTo . "<BR>";

		$mailer->AddBCC("$SendTo");
	        
                $BatchCount++;
		$SendCount++;

	}
		  
	if ($BatchCount > 48) {
		if(!$mailer->Send()) {
    		     echo "There was a problem sending this mail!";
                     }
                     else
                     {
                     echo "Mail sent!";
                }
		$BatchCount = 0;
		$mailer->ClearBCCs();
	}  
	
	
	$HoldRow = mysql_fetch_array($HoldResult);
	
}
?><BR><?php

if(!$mailer->Send()) {
    echo "There was a problem sending this mail!";
    }
    else
    {
    echo "Mail sent!";
}

.....z
 
I noticed that....I've moved some of the informative stuff to this post, since it's the How To thread......z
 
Back
Top