I am trying to create a PHP function to send an e-mail using SMTP with an attachment. I am having a hard time trying to create the MIME headers as I want the body to include text in HTM format and the file to be attached.I am using a very old version of PHP (4.3.8) and this is the only method that is working. Tried PEAR, but won’t authenticate the SMTP correctly.
This is what I have so far: I have edited this code as now I get the message correctly, but the file is corrupt. I changed the file into a text file and it starts out fine but then there appears a lot of garbage text.
$newLine = "\r\n";
$attachment="myFile.zip";
$message = "<br><h1><center>TEST MESSAGE</center></h1>" ;
//Body
$headers .= "Content-Type: multipart/mixed;" . $newLine;
$headers .= " boundary=\"_e9e06aa5-1550-464d-ace4-e85b575d1899_\"" . $newLine . $newLine;
$newLine . $newLine;
$headers .= "--_e9e06aa5-1550-464d-ace4-e85b575d1899_" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
$headers .= "Content-Transfer-Encoding: quoted-printable" . $newLine;
$headers .= " boundary=\"_7fdd1316-6f68-41bb-93f7-134933fc9aad_\"" . $newLine . $newLine;
$headers .= $message . $newLine;
//$headers .= "--_7fdd1316-6f68-41bb-93f7-134933fc9aad_--" . $newLine; // If I leave this line it appears in the end of the message area.
//Attachment
$headers .= "--_e9e06aa5-1550-464d-ace4-e85b575d1899_" . $newLine;
$headers .= "Content-Transfer-Encoding: base64" . $newLine;
$headers .= "Content-Type: text/plain;" . $newLine;
$headers .= "Content-Disposition: attachment;" . $newLine;
$headers .= " filename=" . $attachment . $newLine . $newLine;
$handle = fopen($attachment, "rb");
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, filesize($attachment));
}
fclose($handle);
$contents = base64_encode($contents);
$headers .= $contents . $newLine;
$headers .= "--_e9e06aa5-1550-464d-ace4-e85b575d1899_--" . $newLine;
What about using ready class like PHPMailer? It's much much eaysier. And there is version for PHP4.
Example:
require_once '../class.phpmailer.php';
$mail = new PHPMailer();
$mail->AddReplyTo('name@yourdomain.com', 'First Last');
$mail->AddAddress('whoto@otherdomain.com', 'John Doe');
$mail->SetFrom('name@yourdomain.com', 'First Last');
$mail->AddReplyTo('name@yourdomain.com', 'First Last');
$mail->Subject = 'PHPMailer Test Subject via mail()';
$mail->MsgHTML('Hello world');
$mail->AddAttachment('file.zip');
$mail->Send();
Making custom headers can make headache.