Jump to content

mail() with zip file attachments


mattspriggs28

Recommended Posts

Hi,

 

I have a script that generates a password protected zip file, attaches to an email and sends.

 

The email is sent successfully and received. However, the zip file is not attached. The weird thing is that the size of the email implies that there is an attachment.

 

I've tried in a few different mail clients to see if it was my own that was blocking the zip attachment, but the others are exactly the same.

 

I've also tried generating the zip file without a password and attaching, but again with no luck.

 

Just to further explain, the file needs to be stored within a password protected zip as it will contain confidential information.

 

Here's my code:

 

// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;

$subject = $myForm['surveyType'] . ' : ' . REFERRAL_SUBJ;

// generate the zip file and attach
$password = REFERRAL_PWD;
$outfile = 'referral.zip';

// create file with body inside it
$refFile = time().".html";
$fh = fopen($refFile, 'w') or die("can't open file");
$refData = $smarty->fetch(REFERRAL_BODY_TPL);
fwrite($fh, $refData);
fclose($fh);	

system("zip -P $password $outfile $refFile");

// Read ZIP file into string
$zipDoc = file_get_contents($outfile);
$attachment = chunk_split(base64_encode($zipDoc));

// main header (multipart mandatory)
$headers = "From: " . REFERRAL_MAIL_FROM . $eol;
$headers .= "Reply-To: " . REFERRAL_MAIL_REPLY . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol . $eol;
// message
$headers .= "--" . $separator . $eol;
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"" . $eol;
$headers .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
$headers .= $body . $eol . $eol;
$headers .= "--" . $separator . "--" . $eol . $eol;
// attachment
$headers .= "--" . $separator . $eol;
$headers .= "Content-Type: application/zip; name=\"" . $outfile . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: base64" . $eol;
$headers .= "Content-Disposition: attachment; filename=\"" . $outfile . "\"" . '\r\n\r\n';
$headers .= $attachment . '\r\n\r\n';
$headers .= "--" . $separator . "--";
// send message

$res = mail(REFERRAL_EMAIL_ADDRESS, $subject, "", $headers);

unlink('referral.zip');
unlink($refFile);

 

Any help is much appreciated.

Link to comment
https://forums.phpfreaks.com/topic/265900-mail-with-zip-file-attachments/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.