문제

As I'm working on building and sending email in PHP I've noticed that sometimes people put the code for the message and file attachment in the headers and sometimes in the body. They both work. So what's more correct, or does it make a difference?

Here's example code: In the headers

if (is_uploaded_file($attachment)) {
  $file = fopen($attachment, 'rb');
  $data = fread($file, filesize($attachment));
  fclose($file);

  $data = chunk_split(base64_encode($data));
  $uid = md5(uniqueid(time()));

  $headers = "From: $from\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-Type: multipart/mixed; boundary=\"{$uid}\"\r\n\r\n";

  $headers .= "--{$uid}\r\n";
  $headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n\r\n";
  $headers .= $message. "\r\n\r\n";

  $headers .= "--{$uid}\r\n";
  $headers .= Content-Type: {$att_type}; name=\"{$att_type}\"\r\n";
  $headers .= Content-Transfer-Encoding: base64\r\n";
  $headers .= Content-Disposition: attachment; filename=\"{$att_name}\"\r\n\r\n";
  $headers .= $data . "\r\n\r\n";
  $headers .= "--{$uid}--\r\n";
}
  mail($to, $subject, $message, $headers);

Same code in the message (body):

if (is_uploaded_file($attachment)) {
  $file = fopen($attachment, 'rb');
  $data = fread($file, filesize($attachment));
  fclose($file);

  $data = chunk_split(base64_encode($data));
  $uid = md5(uniqueid(time()));

  $headers = "From: $from\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-Type: multipart/mixed; boundary=\"{$uid}\"\r\n\r\n";

  $message = "This is a multi-part message in MIME format.\r\n";
  $message .= "--{$uid}\r\n";
  $message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n\r\n";
  $message .= $msg. "\r\n\r\n";

  $message .= "\r\n--{$uid}\r\n";
  $message .= Content-Type: {$att_type}; name=\"{$att_type}\"\r\n";
  $message .= Content-Transfer-Encoding: base64\r\n";
  $message .= Content-Disposition: attachment; filename=\"{$att_name}\"\r\n\r\n";
  $message .= $data . "\r\n";
  $message .= "--{$uid}--\r\n";
}
  mail($to, $subject, $message, $headers);

Assuming both of these work, is one method better than the other? When or why does it matter, or does it matter? I can't seem to find an answer to this.

도움이 되었습니까?

해결책

It should be in the body - as per the spec.

다른 팁

It shouldn't matter; the header and message are ultimately just concatenated to each other. That said, by definition the headers of an email end at the first empty line. So, it's probably safer going forward to put the attachment in $message, just in case mail() ever starts stripping extra line breaks from headers.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top