Search code examples
csvphpfgetcsv

Sending php mail to csv list


Im trying to write a simple script to send a message to .csv list of e-mail addresses like this:

[email protected],
[email protected],
[email protected],

Here is what I have tried:

<?
$csv = array();
$file = fopen('test.csv', 'r');

while (($result = fgetcsv($file)) !== false){
$csv[] = $result;   

$to          = $result[0];

$subject = "My mail subject";


$message .= '<html><body>';
$message .= 'My message here';
$message .= "</body></html>";


$from = "[email protected]";
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $from . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

mail($to, $subject, $message, $headers);
}

fclose($file);
?>

But the message is sent three times, and includes the message three times in the body. How can I make the message only be included and sent one time to each line?


Solution

  • You should remove $subject, $message, $from and $headers definition from the while loop. Define all of them before and in the while define only the $to field and keep the mail() command.