PHP Mail ()로 첨부 파일을 보내시겠습니까?


224

우편으로 PDF를 보내야합니까? 가능합니까?

$to = "xxx";
$subject = "Subject" ;
$message = 'Example message with <b>html</b>';
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: xxx <xxx>' . "\r\n";
mail($to,$subject,$message,$headers);

내가 무엇을 놓치고 있습니까?

php 

16
와 첨부 파일을 보내려면 mail()기능이 방법은 당신이 당신의 시간을 위해, 예상보다 단단하다, 사용하려고 PHPMailer
— 미하이 Iorga

1
아니면 그냥 연결할 수 있습니까?

@mihai lorga 서버 측 설치가 필요하지 않습니까? 확장 프로그램이나 플러그인이 없으면 가능할 것입니다.


2
@ChristianNikkanen 그것은 잘 설정된 스크립트 일뿐 만 아니라 달성하기 어려운 많은 기능을 가지고 있습니다. 바퀴를 재발 명하는 이유는 무엇입니까? 추가 플러그인을 사용하지 않습니다.
— Mihai Iorga

답변:


310

의견에 @MihaiIorga에 동의합니다 – PHPMailer 스크립트를 사용하십시오. 더 쉬운 옵션을 원하기 때문에 거부하는 것처럼 들립니다. PHPMailer 는 PHP의 내장 mail()함수를 사용 하는 것보다 훨씬 쉬운 옵션 입니다. PHP의 mail()기능은 실제로 좋지 않습니다.

PHPMailer를 사용하려면 :

  • 여기에서 PHPMailer 스크립트를 다운로드하십시오 : http://github.com/PHPMailer/PHPMailer
  • 아카이브를 추출하고 스크립트 폴더를 프로젝트의 편리한 위치에 복사하십시오.
  • 기본 스크립트 파일 포함 require_once('path/to/file/class.phpmailer.php');

이제 첨부 파일이 포함 된 이메일을 보내는 것은 엄청나게 어려운 일부터 엄청나게 쉬워졌습니다.

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$email = new PHPMailer();
$email->SetFrom('you@example.com', 'Your Name'); //Name is optional
$email->Subject   = 'Message Subject';
$email->Body      = $bodytext;
$email->AddAddress( 'destinationaddress@example.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();

그것은 단지 한 줄 $email->AddAttachment();입니다. 더 쉽게 요청할 수 없었습니다.

PHP mail()기능을 사용하면 코드 스택을 작성하게되며 버그를 찾기가 정말 어려울 것입니다.


1
예, 쉬워요 phpMailer의 요점은 복잡한 작업을 수행하므로 필요하지 않습니다. 그렇기 때문에 읽기가 복잡합니다. 단순히 텍스트 전용 전자 메일을 보내더라도 phpMailer를 선호 mail()하지만 첨부 파일을 사용 하는 것은 결코 쉬운 일이 아닙니다.
— SDC

4
나는 동일했다-이미 코드에 이미 있기 때문에 mail ()을 사용하고 싶었다. PHPMAILER는 첨부 파일 전송에 5 분도 걸리지 않았습니다!
— James Wilson

108
이 질문을 통해 mail()기능을 사용하여 첨부 파일을 추가 하는 방법에 대한 답변을 찾았습니다 . 이 대답은 내가 그렇게하는 데 도움이되지 않습니다.
— Cypher

19
이것은 질문에 대한 답변이 아닙니다. PHPMailer로 첨부 파일을 보내는 방법은 PHP의 mail ()로 첨부 파일을 보내는 방법이 아닙니다.
— Toby

4
이 답변은 프로젝트에서 사용하는 라이센스도 무시합니다. PHPMailer를 사용하면 LGPL 라이센스 문제를 방지하기 위해 소스에서 패키지를 제외해야합니다.
— Axle

190

다음 코드를 사용해보십시오.

    $filename = 'myfile';
    $path = 'your path goes here';
    $file = $path . "/" . $filename;

    $mailto = 'mail@mail.com';
    $subject = 'Subject';
    $message = 'My message';

    $content = file_get_contents($file);
    $content = chunk_split(base64_encode($content));

    // a random hash will be necessary to send mixed content
    $separator = md5(time());

    // carriage return type (RFC)
    $eol = "\r\n";

    // main header (multipart mandatory)
    $headers = "From: name <test@test.com>" . $eol;
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    $headers .= "This is a MIME encoded message." . $eol;

    // message
    $body = "--" . $separator . $eol;
    $body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    $body .= "Content-Transfer-Encoding: 8bit" . $eol;
    $body .= $message . $eol;

    // attachment
    $body .= "--" . $separator . $eol;
    $body .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
    $body .= "Content-Transfer-Encoding: base64" . $eol;
    $body .= "Content-Disposition: attachment" . $eol;
    $body .= $content . $eol;
    $body .= "--" . $separator . "--";

    //SEND Mail
    if (mail($mailto, $subject, $body, $headers)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
        print_r( error_get_last() );
    }

2018 년 6 월 14 일 수정

일부 이메일 제공 업체의 사용 편의성을 높이기 위해

$body .= $eol . $message . $eol . $eol; 과 $body .= $eol . $content . $eol . $eol;


$ uid가 사용되지 않은 것 같습니다.
— Edd

누군가 OP의 코드가이라고 말한 이후 Content-Type이 아니라 라는 의견이어야한다고 대답했습니다 . 의견을 게시 할 담당자가 충분하지 않아 답변을 삭제하도록 신고했기 때문에 본인을 대신하여 의견을 게시하고 있습니다. 'Example message with <b>html</b>'text/htmltext/plain
— Adi Inbar

이 코드에서 $ path 및 $ filename을 정의해야합니까? 그리고 $ filename = $ _FILES [ 'userfile'] [ 'tmp_name']; ?
— malfy

왜 $file그것을 참조한 후에 선언 $filename합니까?
— Kolob Canyon

2
PHPMailer의 문서에서 ... "전자 메일을 올바르게 포맷하는 것은 놀랍게도 어려운 일입니다. 수많은 중복 RFC가 있으며, 엄청나게 복잡한 포맷팅 및 인코딩 규칙을 엄격히 준수해야합니다. 온라인에서 찾을 수있는 대부분의 코드는 mail () 함수를 직접 사용합니다. "정말 잘못입니다!" ... 사실입니다! 이 답변과 같은 것을 사용하여 첨부 파일이있는 메일을 보냈는데 효과가있었습니다! 며칠 후에 만 ​​Gmail에서 첨부 파일이 제대로 표시되는 반면 다른 제공 업체는 base64 콘텐츠를 메일에 직접 인라인으로 표시합니다.
— Aaron Cicali 2016 년

134

PHP 5.5.27 보안 업데이트

$file = $path.$filename;
$content = file_get_contents( $file);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);

// header
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";

// message & attachment
$nmessage = "--".$uid."\r\n";
$nmessage .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$nmessage .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$nmessage .= $message."\r\n\r\n";
$nmessage .= "--".$uid."\r\n";
$nmessage .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$nmessage .= "Content-Transfer-Encoding: base64\r\n";
$nmessage .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$nmessage .= $content."\r\n\r\n";
$nmessage .= "--".$uid."--";

if (mail($mailto, $subject, $nmessage, $header)) {
    return true; // Or do something here
} else {
  return false;
}

$ filename을 정의하지 않았습니다. 그것은 무엇입니까? 파일 경로?
— Jon

3
@ 존. $ filename은 파일의 실제 이름이고 $ path는 파일 이름이없는 실제 파일 경로입니다. 나는 변수를 선언하고 기관 충분히 설명했다 생각
— 사이먼 Mokhele

함수 mail_attachment ($ filename, $ path, $ mailto, $ from_mail, $ from_name, $ replyto, $ subject, $ message)를 정의하지 않으려는 경우 함수에 있어야 함
— Jon

3
여러 첨부 파일을 보내는 경우-로 MIME 부분을 분리 $nmessage .= "--".$uid."\r\n";하고 최종 MIME 부분 $nmessage .= "--".$uid."--";다음에 (위 그림 참조)를 사용하십시오.
— rinogo

2
이것은 바보 같은 phpmailer 일을 시도하는 두통으로 마침내 효과가있었습니다.
— E.Arrowood

22

Swiftmailer 는 사용하기 쉬운 또 다른 스크립트로, 이메일 주입 을 자동으로 방지 하고 첨부 파일을 쉽게 만들 수 있습니다. 또한 PHP의 내장 mail()함수를 사용하지 않는 것이 좋습니다 .

쓰다:

  • Swiftmailer를 다운로드 하고 lib폴더를 프로젝트에 배치하십시오
  • 다음을 사용하여 기본 파일 포함 require_once 'lib/swift_required.php';

이제 메일을 보낼 때 코드를 추가하십시오.

// Create the message
$message = Swift_Message::newInstance()
    ->setSubject('Your subject')
    ->setFrom(array('webmaster@mysite.com' => 'Web Master'))
    ->setTo(array('receiver@example.com'))
    ->setBody('Here is the message itself')
    ->attach(Swift_Attachment::fromPath('myPDF.pdf'));

//send the message          
$mailer->send($message);

더 많은 정보와 옵션은 Swiftmailer Docs 에서 찾을 수 있습니다 .


6
당신이 제 3 자 라이브러리를 dwonload을 제공 일으킬 것 같아요
— vladkras

PHPMailer는 타사가 아닙니까? 또는 @MatthewJohnson이 swiftmailer의 maintners를 만들었거나 의미하는 것을 의미합니까? 해결책이 좋고 효과가있는 한
— 다운 보트는 적절하지 않습니다

1
@Xsmael, PHPMailer는 분명히 제 3 자입니다 :) 솔루션이 작동하는 것처럼 적어도 적어도 downvotes에 동의하지 않습니다. 그러나 사람들은 원하는대로 투표 할 수 있으며, 투표율은 하락세를 부정하는 것 이상입니다.
— Matthew Johnson

17

첨부 파일이 포함 된 이메일을 보내려면 혼합 유형이 이메일에 포함되도록 지정하는 멀티 파트 / 혼합 MIME 유형을 사용해야합니다. 또한 multipart / alternative MIME 형식을 사용하여 전자 메일의 일반 텍스트 버전과 HTML 버전을 모두 보내려고합니다. 예를 살펴보십시오.

<?php 
//define the receiver of the email 
$to = 'youraddress@example.com'; 
//define the subject of the email 
$subject = 'Test email with attachment'; 
//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: webmaster@example.com\r\nReply-To: webmaster@example.com"; 
//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('attachment.zip'))); 
//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

Hello World!!! 
This is simple text email message. 

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

<h2>Hello World!</h2> 
<p>This is something with <b>HTML</b> formatting.</p> 

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

--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: application/zip; name="attachment.zip"  
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_sent = @mail( $to, $subject, $message, $headers ); 
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed"; 
?>

보시다시피 첨부 파일이 포함 된 전자 메일을 보내는 것은 쉽습니다. 앞의 예에서는 multipart / mixed MIME 유형이 있으며 그 안에는 두 가지 버전의 전자 메일을 지정하는 multipart / alternative MIME 유형이 있습니다. 메시지에 첨부 파일을 포함 시키려면 지정된 파일의 데이터를 문자열로 읽고 base64로 인코딩 한 다음 더 작은 청크로 분할하여 MIME 사양과 일치하는지 확인한 다음 첨부 파일로 포함시킵니다.

여기 에서 찍은 .


15
OP 의견에 추가 한 링크의 내용 복사 / 붙여 넣기
— Mark

좋은 스 니펫이지만 경계 문자열 뒤에 추가 줄 바꿈을 제공해야 작동합니다. PHP 파일의 줄 끝 부분과 관련이 있다고 생각합니다. 내 편집기의 기본값은 LF이지만 표준에 따르면 CRLF (carriage return aswell)가 필요합니다.
— Ogier Schelvis

9

이것은 나를 위해 작동합니다. 또한 여러 첨부 파일도 첨부합니다. 용이하게

<?php

if ($_POST && isset($_FILES['file'])) {
    $recipient_email = "recipient@yourmail.com"; //recepient
    $from_email = "info@your_domain.com"; //from email using site domain.
    $subject = "Attachment email from your website!"; //email subject line

    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
    $attachments = $_FILES['file'];

    //php validation
    if (strlen($sender_name) < 4) {
        die('Name is too short or empty');
    }
    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
        die('Invalid email');
    }
    if (strlen($sender_message) < 4) {
        die('Too short message! Please enter something');
    }

    $file_count = count($attachments['name']); //count total files attached
    $boundary = md5("specialToken$4332"); // boundary token to be used

    if ($file_count > 0) { //if attachment exists
        //header
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "From:" . $from_email . "\r\n";
        $headers .= "Reply-To: " . $sender_email . "" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";

        //message text
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($sender_message));

        //attachments
        for ($x = 0; $x < $file_count; $x++) {
            if (!empty($attachments['name'][$x])) {

                if ($attachments['error'][$x] > 0) { //exit script and output error if we encounter any
                    $mymsg = array(
                        1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
                        2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                        3 => "The uploaded file was only partially uploaded",
                        4 => "No file was uploaded",
                        6 => "Missing a temporary folder");
                    die($mymsg[$attachments['error'][$x]]);
                }

                //get file info
                $file_name = $attachments['name'][$x];
                $file_size = $attachments['size'][$x];
                $file_type = $attachments['type'][$x];

                //read file 
                $handle = fopen($attachments['tmp_name'][$x], "r");
                $content = fread($handle, $file_size);
                fclose($handle);
                $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                $body .= "--$boundary\r\n";
                $body .= "Content-Type: $file_type; name=" . $file_name . "\r\n";
                $body .= "Content-Disposition: attachment; filename=" . $file_name . "\r\n";
                $body .= "Content-Transfer-Encoding: base64\r\n";
                $body .= "X-Attachment-Id: " . rand(1000, 99999) . "\r\n\r\n";
                $body .= $encoded_content;
            }
        }
    } else { //send plain email otherwise
        $headers = "From:" . $from_email . "\r\n" .
                "Reply-To: " . $sender_email . "\n" .
                "X-Mailer: PHP/" . phpversion();
        $body = $sender_message;
    }

    $sentMail = @mail($recipient_email, $subject, $body, $headers);
    if ($sentMail) { //output success or failure messages
        die('Thank you for your email');
    } else {
        die('Could not send mail! Please check your PHP mail configuration.');
    }
}
?>

이 코드는 유효성 검사가 부족하고 상황에 맞는 사용자 입력이 없어 헤더 삽입 공격에 취약합니다.
— Synchro

@Synchro .. 이것은 여러 개의 첨부 파일에 대해 찾은 유일한 코드입니다. 안전한 방법으로 사용하는 방법을 제안 해 주시겠습니까?
— NMathur

7

형식이 잘못된 첨부 파일로 잠시 고생 한 후 이것은 내가 사용한 코드입니다.

$email = new PHPMailer();
$email->From      = 'from@somedomain.com';
$email->FromName  = 'FromName';
$email->Subject   = 'Subject';
$email->Body      = 'Body';
$email->AddAddress( 'to@somedomain.com' );
$email->AddAttachment( "/path/to/filename.ext" , "filename.ext", 'base64', 'application/octet-stream' );
$email->Send();

6

작업 개념 :

if (isset($_POST['submit'])) {
    $mailto = $_POST["mailTo"];
    $from_mail = $_POST["fromEmail"];
    $replyto = $_POST["fromEmail"];
    $from_name = $_POST["fromName"];
    $message = $_POST["message"];
    $subject = $_POST["subject"];

    $filename = $_FILES["fileAttach"]["name"];
    $content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));

    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: " . $from_name . " <" . $from_mail . ">\r\n";
    $header .= "Reply-To: " . $replyto . "\r\n";

    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--" . $uid . "\r\n";

// You add html "Content-type: text/html; charset=utf-8\n" or for Text "Content-type:text/plain; charset=iso-8859-1\r\n" by I.khan
    $header .= "Content-type:text/html; charset=utf-8\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";

// User Message you can add HTML if You Selected HTML content
    $header .= "<div style='color: red'>" . $message . "</div>\r\n\r\n";

    $header .= "--" . $uid . "\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n"; // For Attachment
    $header .= $content . "\r\n\r\n";
    $header .= "--" . $uid . "--";
    if (mail($mailto, $subject, "", $header)) {
        echo "<script>alert('Success');</script>"; // or use booleans here
    } else {
        echo "<script>alert('Failed');</script>";
    }
}

6

지정된 첨부 형식 ( application/octet-stream) 으로 인해 위의 답변 중 어느 것도 효과가 없었습니다 . application/pdfPDF 파일로 최상의 결과를 얻으려면 사용하십시오 .

<?php

// just edit these 
$to          = "email1@domain.com, email2@domain.com"; // addresses to email pdf to
$from        = "sent_from@domain.com"; // address message is sent from
$subject     = "Your PDF email subject"; // email subject
$body        = "<p>The PDF is attached.</p>"; // email body
$pdfLocation = "./your-pdf.pdf"; // file location
$pdfName     = "pdf-file.pdf"; // pdf file name recipient will get
$filetype    = "application/pdf"; // type

// creates headers and mime boundary
$eol = PHP_EOL;
$semi_rand     = md5(time());
$mime_boundary = "==Multipart_Boundary_$semi_rand";
$headers       = "From: $from$eolMIME-Version: 1.0$eol" .
    "Content-Type: multipart/mixed;$eol boundary=\"$mime_boundary\"";

// add html message body
$message = "--$mime_boundary$eol" .
    "Content-Type: text/html; charset=\"iso-8859-1\"$eol" .
    "Content-Transfer-Encoding: 7bit$eol$eol$body$eol";

// fetches pdf
$file = fopen($pdfLocation, 'rb');
$data = fread($file, filesize($pdfLocation));
fclose($file);
$pdf = chunk_split(base64_encode($data));

// attaches pdf to email
$message .= "--$mime_boundary$eol" .
    "Content-Type: $filetype;$eol name=\"$pdfName\"$eol" .
    "Content-Disposition: attachment;$eol filename=\"$pdfName\"$eol" .
    "Content-Transfer-Encoding: base64$eol$eol$pdf$eol--$mime_boundary--";

// Sends the email
if(mail($to, $subject, $message, $headers)) {
    echo "The email was sent.";
}
else {
    echo "There was an error sending the mail.";
}

$ headers = "보낸 사람 : $ from $ eolMIME- 버전 : 1.0 $ eol"은 $ eolMIME에서 정의되지 않은 변수 오류를 계속 발생시킵니다.
— 반동

흠 ... 교체 "From: $from$eolMIME-Version: 1.0$eol"로"From: $from" . "$eolMIME-Version: 1.0$eol"
— omikes

어쩌면 PHP의 일부 버전에서와 같이 두 개의 변수를 추가하지 못하게 할 수도 있습니다. 미안합니다. 사실 당신의 모든 인스턴스를 대체 할 수있는 많은 사건이있다 $eol과 " . "$eol하나가 급습 하락에 그 모든 일이 방법은.
— omikes

2
            $to = "to@gmail.com";
            $subject = "Subject Of The Mail";
            $message = "Hi there,<br/><br/>This is my message.<br><br>";

            $headers = "From: From-Name<from@gmail.com>";
// boundary
            $semi_rand = md5(time());
            $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

// headers for attachment
            $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

// multipart boundary
            $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/html; charset=ISO-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";

                $message .= "--{$mime_boundary}\n";
                $filepath = 'uploads/'.$_FILES['image']['name'];
                move_uploaded_file($_FILES['image']['tmp_name'], $filepath); //upload the file
                $filename = $_FILES['image']['name'];
                $file = fopen($filepath, "rb");
                $data = fread($file, filesize($filepath));
                fclose($file);
                $data = chunk_split(base64_encode($data));
                $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$filename\"\n" .
                        "Content-Disposition: attachment;\n" . " filename=\"$filename\"\n" .
                        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
                $message .= "--{$mime_boundary}\n";

mail($to, $subject, $message, $headers);

2

HTML 코드 :

<form enctype="multipart/form-data" method="POST" action=""> 
    <label>Your Name <input type="text" name="sender_name" /> </label> 
    <label>Your Email <input type="email" name="sender_email" /> </label> 
    <label>Your Contact Number <input type="tel" name="contactnumber" /> </label>
    <label>Subject <input type="text" name="subject" /> </label> 
    <label>Message <textarea name="description"></textarea> </label> 
    <label>Attachment <input type="file" name="attachment" /></label> 
    <label><input type="submit" name="button" value="Submit" /></label> 
</form> 

PHP 코드 :

<?php
if($_POST['button']){
{
    //Server Variables
    $server_name = "Your Name";
    $server_mail = "your_mail@domain.com";

    //Name Attributes of HTML FORM
    $sender_email = "sender_email";
    $sender_name = "sender_name";
    $contact = "contactnumber";
    $mail_subject = "subject";
    $input_file = "attachment";
    $message = "description";

    //Fetching HTML Values
    $sender_name = $_POST[$sender_name];
    $sender_mail = $_POST[$sender_email];
    $message = $_POST[$message];
    $contact= $_POST[$contact];
    $mail_subject = $_POST[$mail_subject];

    //Checking if File is uploaded
    if(isset($_FILES[$input_file])) 
    { 
        //Main Content
        $main_subject = "Subject seen on server's mail";
        $main_body = "Hello $server_name,<br><br> 
        $sender_name ,contacted you through your website and the details are as below: <br><br> 
        Name : $sender_name <br> 
        Contact Number : $contact <br> 
        Email : $sender_mail <br> 
        Subject : $mail_subject <br> 
        Message : $message.";

        //Reply Content
        $reply_subject = "Subject seen on sender's mail";
        $reply_body = "Hello $sender_name,<br> 
        \t Thank you for filling the contact form. We will revert back to you shortly.<br><br>
        This is an auto generated mail sent from our Mail Server.<br>
        Please do not reply to this mail.<br>
        Regards<br>
        $server_name";

//#############################DO NOT CHANGE ANYTHING BELOW THIS LINE#############################
        $filename= $_FILES[$input_file]['name'];
        $file = chunk_split(base64_encode(file_get_contents($_FILES[$input_file]['tmp_name'])));
        $uid = md5(uniqid(time()));
        //Sending mail to Server
        $retval = mail($server_mail, $main_subject, "--$uid\r\nContent-type:text/html; charset=iso-8859-1\r\nContent-Transfer-Encoding: 7bit\r\n\r\n $main_body \r\n\r\n--$uid\r\nContent-Type: application/octet-stream; name=\"$filename\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"$filename\"\r\n\r\n$file\r\n\r\n--$uid--", "From: $sender_name <$sender_mail>\r\nReply-To: $sender_mail\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$uid\"\r\n\r\n");
        //Sending mail to Sender
        $retval = mail($sender_mail, $reply_subject, $reply_body , "From: $server_name<$server_mail>\r\nMIME-Version: 1.0\r\nContent-type: text/html\r\n");
//#############################DO NOT CHANGE ANYTHING ABOVE THIS LINE#############################

        //Output
        if ($retval == true) {
            echo "Message sent successfully...";
            echo "<script>window.location.replace('index.html');</script>";
        } else {
            echo "Error<br>";
            echo "Message could not be sent...Try again later";
            echo "<script>window.location.replace('index.html');</script>";
        }
    }else{
        echo "Error<br>";
        echo "File Not Found";
    }
}else{
    echo "Error<br>";
    echo "Unauthorised Access";
}

1

나는 내 자신의 이메일 전송 / 인코딩 기능을 작성했다. 이것은 PDF 첨부 파일을 보내는 데 효과적이었습니다. 프로덕션에서 다른 기능을 사용하지 않았습니다.

참고 : \ r \ n을 사용하여 헤더를 분리해야한다는 사양이 상당히 강조되었지만 PHP_EOL을 사용할 때만 작동했습니다. 나는 이것을 Linux에서만 테스트했다. YMMV

<?php
# $args must be an associative array
#     required keys: from, to, body
#          body can be a string or a [tree of] associative arrays. See examples below
#     optional keys: subject, reply_to, cc, bcc
# EXAMPLES:
#    # text-only email:
#    email2(array(
#        'from' => 'noreply@foo.com',
#        'to' => 'jason@jasonwoof.com',
#        'subject' => 'test',
#        # body will be text/plain because we're passing a string that doesn't start with '<'
#        'body' => 'Hi, testing 1 2 3',
#    ));
#
#    # html-only email
#    email2(array(
#        'from' => 'noreply@foo.com',
#        'to' => 'jason@jasonwoof.com',
#        'subject' => 'test',
#        # body will be text/html because we're passing a string that starts with '<'
#        'body' => '<h1>Hi!</h1>I like <a href="http://cheese.com">cheese</a>',
#    ));
#
#    # text-only email (explicitly, in case first character is dynamic or something)
#    email2(array(
#        'from' => 'noreply@foo.com',
#        'to' => 'jason@jasonwoof.com',
#        'subject' => 'test',
#        # body will be text/plain because we're passing a string that doesn't start with '<'
#        'body' => array(
#            'type' => 'text',
#            'body' => $message_text,
#        )
#    ));
#
#    # email with text and html alternatives (auto-detected mime types)
#    email2(array(
#        'from' => 'noreply@foo.com',
#        'to' => 'jason@jasonwoof.com',
#        'subject' => 'test',
#        'body' => array(
#            'type' => 'alternatives',
#            'body' => array(
#                "Hi!\n\nI like cheese",
#                '<h1>Hi!</h1><p>I like <a href="http://cheese.com">cheese</a></p>',
#            )
#        )
#    ));
#
#    # email with text and html alternatives (explicit types)
#    email2(array(
#        'from' => 'noreply@foo.com',
#        'to' => 'jason@jasonwoof.com',
#        'subject' => 'test',
#        'body' => array(
#            'type' => 'alternatives',
#            'body' => array(
#                array(
#                    'type' => 'text',
#                    'body' => "Hi!\n\nI like cheese",
#                ),
#                array(
#                    'type' => 'html',
#                    'body' => '<h1>Hi!</h1><p>I like cheese</p>',
#                ),
#            )
#        )
#    ));
#
#    # email with an attachment
#    email2(array(
#        'from' => 'noreply@foo.com',
#        'to' => 'jason@jasonwoof.com',
#        'subject' => 'test',
#        'body' => array(
#            'type' => 'mixed',
#            'body' => array(
#                "Hi!\n\nCheck out this (inline) image",
#                array(
#                    'type' => 'image/png',
#                    'disposition' => 'inline',
#                    'body' => $image_data, # raw file contents
#                ),
#                "Hi!\n\nAnd here's an attachment",
#                array(
#                    'type' => 'application/pdf; name="attachment.pdf"',
#                    'disposition' => 'attachment; filename="attachment.pdf"',
#                    'body' => $pdf_data, # raw file contents
#                ),
#                "Or you can use shorthand:",
#                array(
#                    'type' => 'application/pdf',
#                    'attachment' => 'attachment.pdf', # name for client (not data source)
#                    'body' => $pdf_data, # raw file contents
#                ),
#            )
#        )
#    ))
function email2($args) {
    if (!isset($args['from'])) { return 1; }
    $from = $args['from'];
    if (!isset($args['to'])) { return 2; }
    $to = $args['to'];
    $subject = isset($args['subject']) ? $args['subject'] : '';
    $reply_to = isset($args['reply_to']) ? $args['reply_to'] : '';
    $cc = isset($args['cc']) ? $args['cc'] : '';
    $bcc = isset($args['bcc']) ? $args['bcc'] : '';

    #FIXME should allow many more characters here (and do Q encoding)
    $subject = isset($args['subject']) ? $args['subject'] : '';
    $subject = preg_replace("|[^a-z0-9 _/#'.:&,-]|i", '_', $subject);

    $headers = "From: $from";
    if($reply_to) {
        $headers .= PHP_EOL . "Reply-To: $reply_to";
    }
    if($cc) {
        $headers .= PHP_EOL . "CC: $cc";
    }
    if($bcc) {
        $headers .= PHP_EOL . "BCC: $bcc";
    }

    $r = email2_helper($args['body']);
    $headers .= PHP_EOL . $r[0];
    $body = $r[1];

    if (mail($to, $subject, $body, $headers)) {
        return 0;
    } else {
        return 5;
    }
}

function email2_helper($body, $top = true) {
    if (is_string($body)) {
        if (substr($body, 0, 1) == '<') {
            return email2_helper(array('type' => 'html', 'body' => $body), $top);
        } else {
            return email2_helper(array('type' => 'text', 'body' => $body), $top);
        }
    }
    # now we can assume $body is an associative array
    # defaults:
    $type = 'application/octet-stream';
    $mime = false;
    $boundary = null;
    $disposition = null;
    $charset = false;
    # process 'type' first, because it sets defaults for others
    if (isset($body['type'])) {
        $type = $body['type'];
        if ($type === 'text') {
            $type = 'text/plain';
            $charset = true;
        } elseif ($type === 'html') {
            $type = 'text/html';
            $charset = true;
        } elseif ($type === 'alternative' || $type === 'alternatives') {
            $mime = true;
            $type = 'multipart/alternative';
        } elseif ($type === 'mixed') {
            $mime = true;
            $type = 'multipart/mixed';
        }
    }
    if (isset($body['disposition'])) {
        $disposition = $body['disposition'];
    }
    if (isset($body['attachment'])) {
        if ($disposition == null) {
            $disposition = 'attachment';
        }
        $disposition .= "; filename=\"{$body['attachment']}\"";
        $type .= "; name=\"{$body['attachment']}\"";
    }
    # make headers
    $headers = array();
    if ($top && $mime) {
        $headers[] = 'MIME-Version: 1.0';
    }
    if ($mime) {
        $boundary = md5('5sd^%Ca)~aAfF0=4mIN' . rand() . rand());
        $type .= "; boundary=$boundary";
    }
    if ($charset) {
        $type .= '; charset=' . (isset($body['charset']) ? $body['charset'] : 'UTF-8');
    }
    $headers[] = "Content-Type: $type";
    if ($disposition !== null) {
        $headers[] = "Content-Disposition: {$disposition}";
    }

    $data = '';
    # return array, first el is headers, 2nd is body (php's mail() needs them separate)
    if ($mime) {
        foreach ($body['body'] as $sub_body) {
            $data .= "--$boundary" . PHP_EOL;
            $r = email2_helper($sub_body, false);
            $data .= $r[0] . PHP_EOL . PHP_EOL; # headers
            $data .= $r[1] . PHP_EOL . PHP_EOL; # body
        }
        $data .= "--$boundary--";
    } else {
        if(preg_match('/[^\x09\x0A\x0D\x20-\x7E]/', $body['body'])) {
            $headers[] = "Content-Transfer-Encoding: base64";
            $data .= chunk_split(base64_encode($body['body']));
        } else {
            $data .= $body['body'];
        }
    }
    return array(join(PHP_EOL, $headers), $data);
}

내 코드가 포함시키지 않은 일부 함수를 호출했음을 깨달았습니다. 그들은 단지 /에서 / cc / etc 값이 합법적임을 확인했습니다. 나는 그것들을 제거했으며 이제이 코드는 그 자체로 작동합니다.
— JasonWoof

-1

이 페이지 에서 코드 복사-mail ()에서 작동

그는 나중에 호출 할 수있는 mail_attachment 함수를 시작합니다. 나중에 첨부 코드를 사용하여 수행합니다.

<?php
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
    }
}

//start editing and inputting attachment details here
$my_file = "somefile.zip";
$my_path = "/your_path/to_the_attachment/";
$my_name = "Olaf Lederer";
$my_mail = "my@mail.com";
$my_replyto = "my_reply_to@mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,\r\ndo you like this script? I hope it will help.\r\n\r\ngr. Olaf";
mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
?>

그는 자신의 페이지에 대한 자세한 내용을 가지고 있으며 주석 섹션의 일부 문제에 답변합니다.


-1

PHP에서 첨부 파일로 이메일을 보내는 100 % 작업 개념 :

if (isset($_POST['submit'])) {
  extract($_POST);
  require_once('mail/class.phpmailer.php');

  $subject = "$name Applied For - $position";
  $email_message = "<div>Thanks for Applying ....</div> ";

  $mail = new PHPMailer;
  $mail->IsSMTP(); // telling the class to use SMTP
  $mail->Host = "mail.companyname.com"; // SMTP server
  $mail->SMTPDebug = 0;
  $mail->SMTPAuth = true;
  $mail->SMTPSecure = "ssl";
  $mail->Host = "smtp.gmail.com";
  $mail->Port = 465;
  $mail->IsHTML(true);
  $mail->Username = "info@companyname.com";  // GMAIL username
  $mail->Password = "mailPassword";          // GMAIL password

  $mail->SetFrom('info@companyname.com', 'new application submitted');
  $mail->AddReplyTo("name@yourdomain.com","First Last");
  $mail->Subject = "your subject";

  $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

  $mail->MsgHTML($email_message);

  $address = 'info@companyname.com';
  $mail->AddAddress($address, "companyname");

  $mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);      // attachment

  if (!$mail->Send()) {
    /* Error */
    echo 'Message not Sent! Email at info@companyname.com';
  } else {
    /* Success */
    echo 'Sent Successfully! <b> Check your Mail</b>';
  }
}

첨부 파일을 사용하여 Google smtp 메일 전송 에이 코드를 사용했습니다 ....

참고 : 여기에서 PHPMailer 라이브러리를 다운로드하십시오-> https://github.com/PHPMailer/PHPMailer

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.