Suppose there is an array of $ file names of the following type:

Array ( [0] => asd.txt [1] => asdd.txt [2] => asddd.txt ) 

This array is passed to the send_mail function, which processes it and sends an email with several attachments. This is in theory, but in practice only the last investment comes. Here is the function:

  function send_mail($email, $subject, $msg, $from, $file) { $boundary = "--" . md5(uniqid(time())); $headers = "MIME-Version: 1.0\n"; $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\n"; $headers .= "From: $from\n"; $multipart = "--$boundary\n"; $multipart .= "Content-Type: text/html; charset=utf-8\n"; $multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n"; $multipart .= "$msg\n\n"; foreach ($file as $key => $value) { $fp = fopen($value, "r"); $file = fread($fp, filesize($value)); $message_part = "--$boundary\n"; $message_part .= "Content-Type: application/octet-stream\n"; $message_part .= "Content-Transfer-Encoding: base64\n"; $message_part .= "Content-Disposition: attachment; filename=\"$value\"\n\n"; $message_part .= chunk_split(base64_encode($file)) . "\n"; } $multipart .= $message_part . "--$boundary--\n"; mail($email, $subject, $multipart, $headers); } 

The question is, accordingly, where is the dog buried?

  • one
    rfc says CRLF , i.e. end the header lines "\ r \ n"; - zb '
  • Thank. By the way, not everything is possible, because when all headers are fixed, files start to arrive at 0kb, in general, where it’s just \ n can be replaced with \ r \ n, in other cases, leave \ n \ n - andreyqin

1 answer 1

Everything, I fixed it myself :) The fact is that for each iteration, foreach again fastened the headers. You just need to bring in foreach $message_part = ""; and inside the loop, add a point in $message_part .= "--$boundary\n"; , so that it holds together, and does not reset the old value.

  • I would pass the line $ message_part = "- $ boundary \ n"; before the cycles in the form of $ multipart. = "- $ boundary \ n"; and the line $ multipart. = $ message_part. "- $ boundary - \ n"; would bring in a loop. So, as you have decided this question, it will be more reasonable not to use $message_part , but continue to merge everything into $multipart - Johny
  • Yes, you can and so. In my case, you can do without $ message_part = ""; get along. Only one point solved the problem :) - andreyqin