I am reading emails from a text file and have to send one email at a time. Everything(sender, subject, body) is constant except for receiver. I have my PHP mailer working and the additional code I am using is:
<?php
if ($_FILES) {
if ($_FILES['file']['name'] != "") {
if (isset($_FILES) && $_FILES['file']['type'] != 'text/plain') {
echo "<span>File could not be accepted ! Please upload any '*.txt' file. </span>";
exit();
}
echo "<center><span id='Content'>Contents of ".$_FILES['file']['name']." File</span></center>";
$fileName = $_FILES['file']['tmp_name'];
$file = fopen($fileName,"r") or exit("Unable to open file!");
$string = file_get_contents("$fileName"); // Load text file contents
$pattern = '/[a-z0-9_\-\+]+@[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i';
preg_match_all($pattern, $string, $matches);
$output = var_export($matches[0]);
foreach ($output as $item) {
echo "$item
";
$output = $item;
}
print_r($output);
} else {
if (isset($_FILES) && $_FILES['file']['type'] == '') {
echo "<span>Please Choose a file by click on 'Browse' or 'Choose File' button.</span>";
}
}
}
?>
You can set multiple recipients to a single message and set the SingleTo to true.
$recipient_addresses = array();
....
$message = new \PHPMailer;
$message->SingleTo = true;
....
foreach($recipient_addresses as $email) $message->addAddress($email);
....
Please not that the the SingleTo is only supported in "mail" and "sendmail" transports, not in "SMTP".
If you use the SMTP transport, just loop the send for each address one-by-one. Just call $message->addAddress one time to pass just one address for each instance of the PHPMailer class, but create multiple instance, one-by-one:
1. $message = new \PHPMailer;
2. $message->addAddress($email);
3. fill other data, but don't set the SingleTo property value, keep it default (false).
4. $message->send();
5. unset($message);
Please also be aware of the fact that SingleTo is planned to be deprecated in the release of PHPMailer 6.0, and removed in 7.0.