Search code examples
phpemailphpmailermailer

PHPMailer get addresses from file


I'm trying to get addresses from a simple text file, so people who don't understand code can still add/remove or change the adresses.

Phpmailer is working totally fine when I set up an address normally, writing it directly in the code, and even with an array and a foreach.

So at the moment I have this :

mail.php :

//all phpmailer settings on $mail var
$addresses = file('mail.txt', FILE_IGNORE_NEW_LINES);
foreach($addresses as $email) {
    echo "$email<br>";
    $mail->addAddress($email);
}

mail.txt :

'[email protected]'
'[email protected]'

The echo does return both addresses but the var doesn't seem to work in the addAddress() line, and I get the usual error : Mailer Error: You must provide at least one recipient email address.

Thanks for correcting me if I'm wrong or if you know any other solution that could work !



Okay so here is the working code corrected with the help of Waqas Shahid :

mail.php :

//all phpmailer settings on $mail var
$addresses = file('mail.txt', FILE_IGNORE_NEW_LINES);
foreach($addresses as $email) {
    $email = trim($email);
    $change = array('\n', '\t', '\r');
    $email = str_replace($change, "", $email);
    $mail->addAddress($email);
}

mail.txt :

[email protected]
[email protected]

Solution

  • You should remove single quotes first, then get value line by line and remove whitespaces using trim() then remove '\n', '\t', '\r' using str_replace()