Search code examples
phpemailemail-headers

PHP Mail Headers


Essentially what I'm trying to do is attach a file to an email I'm sending out. Simple enough, right? For some reason or another it does not like the following code (presumably because of the headers). Can anyone help?

Thanks in advance!!

$subject = "File ".date("Ymd");
$message = "NONE";
$filename = "test.csv";

$content = chunk_split(base64_encode(file_get_contents($filename)));
$uid = md5(uniqid(time()));
$name = basename($file);

$header .= "MIME-Version: 1.0\r\n";
$header .= "From: noreply@x.com\r\n";
$header .= "Reply-To: noreply@x.com\r\n";


$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: text/csv; name=\"".$filename."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."\r\n";
//echo $header;

if (mail($to_email, $subject, $message, $header)) {
    echo "mail send ... OK"; 
} else {
    echo "mail send ... ERROR!";
}

And the error:

Warning: mail() [function.mail]: Bad parameters to mail() function, mail not sent.


Solution

  • Please please please don't build your own MIME emails. Use PHPMailer or Swiftmailer, which do almost everything for you. You can replace you entire script with about 5 or 6 lines of code.

    And best of all, they'll give you far better error messages/diagnostics than the pathetically stupid mail() function ever will.