2012-01-31 3 views
1

완성 된 전자 메일을 첨부 파일이있는 사용자에게 보내는 웹 응용 프로그램을 설정하려고합니다. 전자 메일을 HTML 형식과 텍스트 형식으로 모두 사용하여 모든 사용자가 자신의 메일 설정에 관계없이 볼 수 있도록하고 싶습니다. 나는 그것이 작동하도록하는 데 어려움을 겪고있다. 그래서 누군가 내 코드로 문제를 발견 할 수 있는지 궁금했다.HTML/텍스트 PHP를 사용하는 첨부 파일이 포함 된 전자 메일

내가 사용하는 코드는 다음과 같습니다. 이 템플릿은 다른 사이트의 템플릿으로 사용되었지만 읽는 방법을 많이 읽었으므로 어떻게 작동하는지 대략 이해했습니다. 불행히도, 문제를 해결하기위한 충분한 이해가 아닙니다!

$firstname = $_POST['firstname']; 
$email = $_POST['email']; 
//define the receiver of the email 
$to = $email; 
//define the subject of the email 
$subject = "$firstname, thanks for using the One Minute Leveller"; 
//create a boundary string. It must be unique 
//so we use the MD5 algorithm to generate a random hash 
$random_hash = md5(date('r', time())); 
//define the headers we want passed. Note that they are separated with \r\n 
$headers = "From: The Xenon Group\r\nReply-To: [email protected]"; 
//add boundary string and mime type specification 
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; 
//read the atachment file contents into a string, 
//encode it with MIME base64, 
//and split it into smaller chunks 
$attachment = chunk_split(base64_encode(file_get_contents('Level3info.pdf'))); 
//define the body of the message. 
ob_start(); //Turn on output buffering 
?> 
--PHP-mixed-<?php echo $random_hash; ?> 

Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" 

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit 

TEXT E-MAIL GOES HERE. ACTUAL CONTENT REMOVED 

--PHP-alt-<?php echo $random_hash; ?> 

Content-Type: text/html; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit 

<html><h1>HTML CONTENT GOES HERE. ACTUAL CONTENT REMOVED</h1></html> 

--PHP-alt-<?php echo $random_hash; ?>-- 

--PHP-mixed-<?php echo $random_hash; ?> 

Content-Type: application/pdf; name="Level3info.pdf" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

<?php echo $attachment; ?> 

--PHP-mixed-<?php echo $random_hash; ?>-- 

<?php 
//copy current buffer contents into $message variable and delete current output buffer 
$message = ob_get_clean(); 
//send the email 
mail($to, $subject, $message, $headers); 

아무도 도와 줄 수 있습니까?! 당신이 당신의 헤더와 그 허용되지 않는 사이에 공백이 같은 http://pear.php.net/package/Mail/redirected

둘째 배 메일로 라이브러리를 사용 -

+0

이렇게 PHP를 들락날락하지 말 것을 권합니다. 그것은 당신의 코드를 읽기가 어렵게 만든다. – Travesty3

+0

이와 같은 작업에 기존 클래스를 사용하는 것이 좋습니다. http://pear.php.net/manual/en/package.mail.mail-mime.addattachment.php – powtac

답변

2

우선,하지 않는 바퀴를 다시 발명. 메일 RFC에서

:

의 의견과 FWS가 자유롭게 삽입 할 수도 있습니다 표준 여러 곳이 있습니다

. 해당 구문을 수용하기 위해 주석 및/또는 FWS가 발생할 수있는 장소에 대해 "CFWS"에 대한 추가 토큰 이 정의됩니다. 그러나이 표준에서 CFWS가 발생하는 경우 접힌 머리글 필드의 모든 줄이 전체적으로 WSP 문자로 구성된 으로 이루어지며 그 밖의 다른 방법으로는 을 삽입해서는 안됩니다.

종류와 관련,

+0

안녕하세요, 감사합니다. 배 메일 (Pear Mail)은 백만 번 더 쉽게 증명되었습니다! – Chris

1

는 여기에 작동하는지 무엇을 사용합니다. 그것은 ... HTML 버전 대 계정 텍스트 버전으로 단지 HTML 버전을하지 않지만, 아마도 그것은 답으로 여러분을 안내 할 것입니다 :

<?php 
    $mime_boundary = md5(uniqid(time())); 

    // to 
    $to = $_REQUEST["to"]; 
    if (is_array($to)) $to = implode(", ", $to); 

    // from 
    $header = "From:". ($_REQUEST["fromName"] == "" ? $_REQUEST["fromAddress"] : "{$_REQUEST["fromName"]} <{$_REQUEST["fromAddress"]}>") ."\r\n"; 
    $header .= "MIME-Version:1.0\r\n"; 
    $header .= "Content-Type:multipart/mixed; boundary=\"{$mime_boundary}\"\r\n\r\n"; 

    // message 
    $header .= "--{$mime_boundary}\r\n"; 
    $header .= "Content-Type:text/html; charset=\"ISO-8859-1\"\r\n"; 
    $header .= "Content-Transfer-Encoding:7bit\r\n\r\n"; 
    $header .= "<html><head><style type=\"text/css\">body { font:10pt Arial; }</style></head><body>". str_replace("\r", "", str_replace("\n", "<br />", $_REQUEST["message"])) ."</body></html>\r\n\r\n"; 

    // attachment 
    $attachments = (array)$_REQUEST["attachment"]; 
    $attachmentNames = (array)$_REQUEST["attachmentName"]; 
    for ($i = 0; $i < count($attachments); $i++) 
    { 
     if (empty($attachmentNames[$i])) 
      $attachmentNames[$i] = "attachment". ($i+1) .".txt"; 

     if (!base64_decode($attachments[$i], true)) 
      $attachments[$i] = base64_encode($attachments[$i]); 
     else 
      $attachments[$i] = str_replace("\r", "", str_replace("\n", "", str_replace(" ", "+", $attachments[$i]))); 

     $header .= "--{$mime_boundary}\r\n"; 
     $header .= "Content-Type:application/octet-stream; name=\"{$attachmentNames[$i]}\"\r\n"; 
     $header .= "Content-Transfer-Encoding:base64\r\n"; 
     $header .= "Content-Disposition:attachment; filename=\"{$attachmentNames[$i]}\"\r\n"; 
     $header .= "{$attachments[$i]}\r\n\r\n"; 
    } 

    if (mail($to, $_REQUEST["subject"], "", $header)) 
     echo "SUCCESS"; 
    else 
     echo "FAIL"; 
?> 
+0

답장 시간을내어 주셔서 감사합니다. 실제로는 PEAR 메일 라이브러리를 사용하고 있습니다. 처음부터 모든 것을 수행하는 것보다 훨씬 쉽고 텍스트/HTML 및 첨부 파일을 얻을 수 있습니다! 건배! – Chris

1

은 어쩌면 당신은 PHPmailer에 살펴 봐야합니다. 그것은 당신이 사용하고자하는 모든 기능을 제공하지만, build-in mail() 함수보다 훨씬 더 깔끔하고 표준적인 방법으로 제공됩니다. 그리고 거기에 좋은 자습서가 있습니다.

+0

고맙습니다. 사실 John (위)에서 제안한대로 PEAR Mail을 사용했지만, 아이디어는 동일합니다. 처음부터 모든 것을 코딩하려고하는 것보다는 훨씬 쉽습니다! – Chris

관련 문제