Search code examples
phpemailldapphpmailer

Error in sending mails while giving to address as an array


I have a dynamic table where user names are entered. On submit, the names are queried from LDAP to get the E-Mail ID's and a mail is to be sent to them. My code is as below :

<?PHP
if ($_SERVER["REQUEST_METHOD"] == "POST") 
{
    $email_body = $email_body ."Test";
    require_once("class.phpmailer.php");
    $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->SMTPAuth   = true;                
    $mail->Host       = "***"; 
    $mail->SetFrom('***');
    $mail->Subject    = "Test";
    $mail->MsgHTML($email_body);
    foreach($_POST['Trainee_Name'] as $traineename) //Field Name in the dynamic table
    {   
        $username="***";
        $password="***";
        $lc = ldap_connect("***") or
        die("Couldn't connect to AD!");
        ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_bind($lc,$username,$password);
        $base = "OU=**,DC=**,DC=**";
        $filt = "(&(&(&(objectCategory=person)(objectClass=user)(name=$traineename*))))";
        $sr = @ldap_search($lc, $base, $filt);
        $info = ldap_get_entries($lc, $sr);
        for ($j = 0; $j < $info["count"]; $j++) 
        {
            echo $address=$info[$j]["mail"][0]."<br/>"  ; //echo's the email ID 
            $mail->AddAddress($address);
        }
        if ($j == 0)
        {
            echo "No matches found!";
        }
        ldap_close($lc);
    }       

    if (!$mail->send()) {
            echo "Mailer Error (" . str_replace("@", "&#64;", $row["email"]) . ') ' . $mail->ErrorInfo . '<br />';
            break; //Abandon sending
        } else {
            echo "Message sent";
        }
}
?>

In the output, the LDAP query code echoes the E-Mail ID, but doesn't send a mail. Where could I have gone wrong? I used the links below as a reference :

  1. PHP mailer multiple address
  2. PHPMailer AddAddress()
  3. how to send emails to multiple addresses using phpmailer

Appreciate any suggestion / Assistance.


Solution

  • I suspect that your evil combined echo-array-add-concat operation is appending <br/> to the end of every address, which won't be visible in your browser, but will make every email address invalid. Try this:

    for ($j = 0; $j < $info['count']; $j++) 
    {
        $add = $info[$j]['mail'][0];
        $address[] = $add;
        echo "$add<br/>";
    }