7 days of php add-ons - Day 6: PHPMailer

Thursday, 16 April 2009


Welcome to day six of 7 days of php add-ons.

Today we'll be looking at PHPMailer

After you have been coding for a while it is a good idea to pick up on the things that you do over and over again in your work. With these tasks it is a good idea to find a good implementation of the same task and keep it handy. This will save you from reinventing the wheel and if you know something works and can be reused it will also save you time with testing. One of these tasks that you will do over and over again is sending mail. It is a good idea to have a mailer class that will take the hassle out of sending emails and can be used in different situations e.g. sending attachments etc.

PHPMailer is still in active development and is a clean robust implementation. It is easy to use and does everything it claims to do.

A new version was just released a couple of weeks ago and includes a whole new collection of easy to follow examples that can be seen here. Including an example of how to send SMTP via a MySQL database and sending mail through Gmail.

Here is a simple example:


require_once('../class.phpmailer.php');

$mail = new PHPMailer(); // defaults to using php "mail()"

$body = file_get_contents('contents.html');
$body = eregi_replace("[]",'',$body);

$mail->AddReplyTo("name@yourdomain.com","First Last");

$mail->SetFrom('name@yourdomain.com', 'First Last');

$mail->AddReplyTo("name@yourdomain.com","First Last");

$address = "whoto@otherdomain.com";
$mail->AddAddress($address, "John Doe");

$mail->Subject = "PHPMailer Test Subject via mail(), basic";

$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

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


Once you get it up and running you can stick it inside a function that can handle multiple recipients or attachments, for example:


function sendemail($body, $subject, $recipients = '', $altbody = '', $attachments = '') {
include_once('mailer/class.phpmailer.php');

$mail = new PHPMailer();

$body = eregi_replace("[]",'',$body);

$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "TESTSRV01"; // SMTP server

$mail->From = "info@yourdomain.com";
$mail->FromName = "My system";

$mail->Subject = $subject;

$mail->AltBody = $altbody;

$mail->MsgHTML($body);

$mail->AddAddress("admin@yourdomain.com", "Tim Radnidge");

if ($recipients) {
foreach ($recipients as $recipient) {
$mail->AddAddress($recipient['address'], $recipient['name']);
}
}

if ($attachments) {
foreach ($attachments as $attachment) {
$mail->AddAttachment($attachment);
}
}

if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
return true;
}
}
blog comments powered by Disqus