php发送带附件的邮件

时间:2014-04-03 10:47:33

标签: php email sendmail

这是发送邮件的代码,

<?php
    $owner_email = $_POST["owner_email"];
    $headers = 'From:' . $_POST["email"];
    $subject = 'Visitor : ' . $_POST["name"];
    $messageBody = "";

    if($_POST['name']!='nope'){
        $messageBody .= '<p>Visitor: '. $_POST["name"] . '</p>' . "\n";
        $messageBody .= '<br>' . "\n";
    }
    if($_POST['email']!='nope'){
        $messageBody .= '<p>Email Address: ' . $_POST['email'] . '</p>' . "\n";
        $messageBody .= '<br>' . "\n";
    }else{
        $headers = '';
    }
    if($_POST['state']!='nope'){        
        $messageBody .= '<p>State: ' . $_POST['state'] . '</p>' . "\n";
        $messageBody .= '<br>' . "\n";
    }
    if($_POST['phone']!='nope'){        
        $messageBody .= '<p>Phone Number: ' . $_POST['phone'] . '</p>' . "\n";
        $messageBody .= '<br>' . "\n";
    }   

    if($_POST['message']!='nope'){
        $messageBody .= '<p>Message: '."\n". $_POST['message'] . '</p>' . "\n";
    }

    if($_POST["stripHTML"] == 'true'){
        $messageBody = strip_tags($messageBody);
    }

    try{
        if(!mail($owner_email, $subject, $messageBody, $headers)){
            throw new Exception('mail failed');
        }else{
            echo 'mail sent';
        }
    }catch(Exception $e){
        echo $e->getMessage() ."\n";
    }
?>

如何使用此代码实现附件,我已经尝试通过查看堆栈溢出和其他网站上的一些示例它似乎无法工作..请帮助...

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

工作代码:

<?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.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

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/pdf; name="attachment.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_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"; 
?>

答案 2 :(得分:0)

这可以让我将文件作为附件发送。

<?php
    if($value == "Send")                     // Submit button
    {
        $fileName = $_REQUEST['file'];      

        $to = $_REQUEST['Email'];   
        $subject = "PHP File Manager";
        $message = "download the attached file";
        # Open a file
        $downloadfile = $fileName;
        $file = fopen($downloadfile, "r" );
        if( $file == false )
        {
        echo "Error in opening file";
        exit();
        }

        # Read the file into a variable
        $size = filesize($downloadfile);
        $content = fread( $file, $size);

        # encode the data for safe transit
        # and insert \r\n after every 76 chars.
        $encoded_content = chunk_split( base64_encode($content));

        # Get a random 32 bit number using time() as seed.
        $num = md5( time() );
        $SendEmail ="test@gmail.com";
        $header = 'From: ' . $SendEmail . "\r\n" .
        'Reply-To: ' . $SendEmail . "\r\n"; 

        # Define the main headers.
        //$header = "From:Test\r\n";
        $header .= "MIME-Version: 1.0\r\n";
        $header .= "Content-Type: multipart/mixed; ";
        $header .= "boundary=$num\r\n";
        $header .= "--$num\r\n";

        # Define the message section
        $header .= "Content-Type: text/plain\r\n";
        $header .= "Content-Transfer-Encoding:8bit\r\n\n";
        $header .= "$message\r\n";
        $header .= "--$num\r\n";

        # Define the attachment section
        $header .= "Content-Type:  multipart/mixed; ";
        $header .= "name=\"$fileName\"\r\n";
        $header .= "Content-Transfer-Encoding:base64\r\n";
        $header .= "Content-Disposition:attachment; ";
        $header .= "filename=\"$fileName\"\r\n\n";
        $header .= "$encoded_content\r\n";
        $header .= "--$num--";

        # Send email now
        $retval = mail ( $to, $subject, "", $header );
        if( $retval == true )
        {
            echo "success";
        }
    }
?>