How do I mail a message to a group of people?

Started by chinmay.sahoo, 07-05-2016, 04:34:26

Previous topic - Next topic

chinmay.sahooTopic starter

In many cases, it's useful to be able to mail a message to more than one person at a time—for example, if you're sending a newsletter, a message to a group mailing list, a site update notification to the IT staff, a feature freeze notification to a development team, and so on. However, in certain circumstances, sending unsolicited email to a group of people can also be called spamming—something I'm sure you won't be doing with PHP!

If you're using PEAR::Mail_Mime, you have the option to send group email by adding BCC or CC headers to the email message. This approach may not suit your requirements, though—listing all the addresses from an especially large distribution list in the header of a single email can quickly overwhelm your email server.

A better approach is to send each email individually, reusing the same instance of the PEAR::Mail_Mime class for each new message.

Solution
In this hypothetical example, we'll retrieve a list of names and email addresses from a discussion forum's member database, and reuse one instance of the PEAR::Mail_Mime class to send an email to each of those addresses:

Quote<?php
error_reporting(E_ALL);
require 'Mail.php';
require 'Mail/mime.php';
/* create the email */
$mime = new Mail_Mime("\r\n");
$mime->addAttachment('php.gif', 'image/gif');
$header = array(
'From'
=> 'me@mydomain.com',
'Subject' => 'Forum Newsletter'
);
$mail = Mail::factory('smtp', array('host'=>'
smtp.mydomain.net
'));
/* go to the database to get the member information */
$dsn = 'mysql:host=localhost;dbname=forum;';
$user = 'user';
$password = 'secret';
try
{
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT member_email, firstname, lastname FROM member';
/* cycle through the list sending the custom emails */
foreach ($dbh->query($sql) as $row)
{
$mime->setTXTBody(
"Howdy {$row['firstname']} {$row['lastname']}");
$body = $mime->get();
$hdrs = $mime->headers( $header);
$succ = $mail->send($row['member_email'], $hdrs, $body);
if (PEAR::isError($succ)){
error_log("Email not sent to {$row['member_email']}: " .
$succ->getMessage());
}
}
}
catch (PDOException $e)
{
echo 'PDO Exception Caught. ';
echo 'Error with the database: <br />';
echo 'SQL Query: ', $sql;
echo 'Error: ' . $e->getMessage();
}
?>