How come [this piece of php code](http://www.emanueleferonato.com/2008/07/22/sending-email-with-multiple-attachments-with-php/) doesn't work with multiple recipient ?

It only works if `$to` has only one adress, like: 

```
$to = 'aa@bb.com';

```

**Edit** 

It works if email adresses are on the same domain.. For instance, if the website is `www.example.com`, emails such as `xxx@example.com` will work but y`yy@other.com` won't.

**Solution**

PHPMailer. It gives an easy way to configure `SMTP`.

**Here is the initial code**

```
<?php

//define the receiver of the email
$to = 'aa@bb.com, cc@dd.com, ee@ff.com';

// array with filenames to be sent as attachment
$files = array("a.zip","b.c","a.html");

// email fields: to, from, subject, and so on
$from = "mail@mail.com"; 
$subject ="My subject"; 
$message = "My message";

// boundary 
$semi_rand = md5(time()); 
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 

// headers for attachment 
$headers = "From: $from";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 

// multipart boundary 
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; 
$message .= "--{$mime_boundary}\n";

// preparing attachments
for($x=0;$x<count($files);$x++){
    $file = fopen($files[$x],"rb");
    $data = fread($file,filesize($files[$x]));
    fclose($file);
    $data = chunk_split(base64_encode($data));
    $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . 
    "Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" . 
    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
    $message .= "--{$mime_boundary}\n";
}

// send

$ok = @mail($to, $subject, $message, $headers); 
if ($ok) { 
    echo "<p>mail sent to $to!</p>"; 
} else { 
    echo "<p>mail could not be sent!</p>"; 
} 

?>

```

**Here is the final code**

```
// PHPMailer
$mail = new PHPMailer;

// setting up PHPMailer
$mail->isSMTP();
$mail->Host = 'host.com';
$mail->SMTPAuth = false;
$mail->Port = xx;

$mail->setFrom($_POST['email'], $_POST['name']);
$mail->Subject = $_POST['subject'];
$mail->msgHTML($_POST['message']);

foreach($contacts as $contact)
    $mail->addAddress($contact['email']);

// If the user has attached some files
foreach ($_FILES as $file)
    $mail->addAttachment($file['tmp_name'], basename($file['name']));

$response = array("status" => $mail->send() ? "sent" : "error");

echo json_encode($response);

```