How to Use PHP Mail to Send to a Mailing List
You can send mail to a mailing list using the PHP "mail" function by storing each email address in an array and looping through the array to send an email to each person. If your mailing list is large, you should throttle the process by sending emails in small groups with a pause between each batch. This reduces the risk of your email being flagged by a recipient email server as spam.
Instructions
-
-
1
Create an array to store the email addresses in the mailing list. For example, type:
<?php
$mailing_list = array("john@example.com", "paula@example.com", "cindy@example.com");
-
2
Create variables to store the subject and message. Use the "wordwrap" function to restrict each line within the message to no more than 70 characters. For example, type:
$subject = "Important Message";
$message = "This is an important reminder that tonight's event will take place at 8:00 p.m.";
$message = wordwrap($message, 70);
-
-
3
Create a variable to store any additional headers you want to include in the message. Separate each header with the carriage return and line feed characters "\r\n." For example, type:
$headers = "From: webmaster@example.com" . "\r\n" . "Reply-To: webmaster@example.com" . "\r\n" . "X-Mailer: PHP/" . phpversion();
-
4
Create variables to hold the throttling parameters. For example, type:
$max_emails_sent = 10;
$sleep_time = 10;
-
5
Create a function that uses the PHP "mail" function to send the email message. Check the return value of the "mail" function to determine whether the function call to "mail" was successful. For example, type:
function mailit($person, $subject, $message, $headers) {
$result = mail($person, $subject, $message, $headers);
if (!$result)
echo ("Mail to " . $person . " was NOT successful!\r\n");
else
echo ("Mail to " . $person . " was successful!\r\n");
}
-
6
Loop through each element in the array of emails and send the email to that person. After the maximum number of emails is sent, pause for the designated number of seconds. For example, type:
$count = 0;
foreach ($mailing_list as $person) {
if ($count > $max_emails_sent) {
sleep($sleep_time);
$count = 0;
}
mailit($person, $subject, $message, $headers);
++$count;
}
-
1
References
- Photo Credit John Foxx/Stockbyte/Getty Images