Send attachments with PHP Mail()?

前端 未结 14 2335
北恋
北恋 2020-11-21 04:46

I need to send a pdf with mail, is it possible?

$to = \"xxx\";
$subject = \"Subject\" ;
$message = \'Example message with html\';
$header         


        
相关标签:
14条回答
  • 2020-11-21 04:57

    After struggling for a while with badly formatted attachments, this is the code I used:

    $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();
    
    0 讨论(0)
  • 2020-11-21 04:58

    To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email.Have a look at the example:

    <?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"; 
    ?>
    

    As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64, split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.

    Taken from here.

    0 讨论(0)
  • 2020-11-21 04:59
                $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);
    
    0 讨论(0)
  • 2020-11-21 05:02

    For PHP 5.5.27 security update

    $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;
    }
    
    0 讨论(0)
  • 2020-11-21 05:03

    Swiftmailer is another easy-to-use script that automatically protects against email injection and makes attachments a breeze. I also strongly discourage using PHP's built-in mail() function.

    To use:

    • Download Swiftmailer, and place the lib folder in your project
    • Include the main file using require_once 'lib/swift_required.php';

    Now add the code when you need to mail:

    // 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);
    

    More information and options can be found in the Swiftmailer Docs.

    0 讨论(0)
  • 2020-11-21 05:04

    HTML Code:

    <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 Code:

    <?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";
    }
    
    0 讨论(0)
提交回复
热议问题