简体   繁体   中英

Trying to automatically send an inline and/or attachment with mail() from a html form, but keep getting binary string

I'm trying to make an email form for a club I'm designing, and I want it to check to see if I'm including an attachment or an inline image with the html email. All is working so far except when I try to include an attachment it times out at 90 seconds and it send a few of the emails and the begining of the are filled with "---- Content-Type: application/pdf; name="BrainMonkey-ooPic-RS.pdf" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="test-RS.pdf" then there is the binary string representing the file and the end there is the html email which was sent less the attachment ofcourse. Here is the code:

<?php 
//------------------------ Check if Subject is filled out ------------------------------>
if (isset($_POST['subject']))
{

//-------------- Upload File from User Computer for attachment ------------------------->
$target_path = "attachments/";
$target_path = $target_path . basename( $_FILES['file']['name']);

if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_path)) {
    $file_location = $target_path;
    $fileatt = $file_location;
    $fileattname =basename($file_location);

    // read file into $data var
    $file = fopen($fileatt, "rb");
    $data = fread($file,  filesize( $fileatt ) );
    fclose($file);

    // split the file into chunks for attaching
    $content = chunk_split(base64_encode($data));
    $isattached = "yes";
    echo "Attachment attached ".$fileattname." uploaded and is good!";
} else {
    $isattached = "no";
    echo "No Attachment sent ".$fileattname;
}

//------------ Upload File from User Computer for inline image ------------------------>
$target_path2 = "attachments/";

$target_path2 = $target_path2 . basename( $_FILES['file2']['name']);

if(move_uploaded_file($_FILES["file2"]["tmp_name"], $target_path2)) {
    $file_location2 = $target_path2;
    $fileatt2 = $file_location2;
    $fileattname2 =basename($file_location2);
    $inline = '<tr><td><center><img src="http://www.mywebsite.com/JWEC/JWECMail/'. $target_path2 .'"></center><br></td></tr>';
    echo "Inline Attached ".$inline;
} else {
    $inline = ' ';
    echo "<br>No Inline Attached ".$inline."<br>";
}       

//------------------- Set up From, Replyto, and $message ------------------------------>
                $name = "ME";
                $from = "myemail@mywebsite.com";
                $replyto= $from;
                $message = $_REQUEST['message']; 

//------------------------ Setup Header -------------------------------------------->
                // handles mime type for better receiving
                if ($isattached == "yes") {
                    $ext = strrchr( $fileatt , '.');
                    echo $ext;
                    $ftype = "";
                    if ($ext == ".doc") $ftype = "application/msword";
                    if ($ext == ".jpg") $ftype = "image/jpeg";
                        if ($ext == ".gif") $ftype = "image/gif";
                    if ($ext == ".png") $ftype = "image/png";
                    if ($ext == ".zip") $ftype = "application/zip";
                        if ($ext == ".pdf") $ftype = "application/pdf";
                    if ($ftype=="") $ftype = "application/octet-stream";
                }
                //$uid = md5(uniqid(time()));


//---------------------------- Connect to DB ------------------------------------------>
        $con = mysql_connect("mywebsitemysql.com","username","password");   
        if (!$con)  
        {   
            die('Could not connect: ' . mysql_error()); 
        }   
        mysql_select_db("database"); 

//----------------------- Select First Names and Emails --------------------------->
        $result = mysql_query("SELECT fname, email FROM  table");   
        if(mysql_num_rows($result) <= 0)    
        {
            echo "<div class=\"box red\"><center>Email Submissions Failed, No members to send to.</center></div>"; 
        }
        else    
        {
            $count = 0;     
            while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) 
            {  
//---------------------- Set To & Subject -------------------------------------------->
                $to = $row['email']; 
                $subjectf = $_POST["subject"];
                $subject = "Here is a " . $subjectf . " for you ";
                $person = $row['fname'];
            $footer = "<br><br> Best Regards,<br> My Website Club  br><br> If you feel we have sent this email to you in error, or if you <br> would like to be removed from future JW Elite Club emails, you may unsubscribe here:<br> http://www.mywebsite.com/JWEC/unsubscribe.php?email=".$to."<br>";
//------------------------- Message --------------------------------------------------->
                $messagehtml = "  
                  <html> 
                     <head></head> 
                      <body>  
                   <table border='0' cellpadding='0' cellspacing='0' align='center' width='550'> 
            <tr><td><img src='http://www.mywebsite.com/JWEC/JWECMail/include/header.jpg' width='550' alt='My Website Club'><br><br></td></tr> 
            <tr><td>Dear " . $person . ",<br><br></td></tr>
        <tr><td>" . $message . "<br><br></td></tr>
            ".$inline."
        <tr><td>" . $footer . "<br></td></tr>
        <tr><td><img src='http://www.mywebsite.com/JWEC/JWECMail/include/footer.jpg' width='550' alt='My Company and My Website - Keep Walking'><br><br></td></tr>
            </table> 
            </body> 
            </html> 
            ";

//------------------ Set Headers ------------------------------------------------->
            // build the headers for attachment and html
                "--{$mime_boundary}--\n";
                $h = "From: $name<$from>" . "\r\n";
                $h .= "Reply-To: $from"."\r\n";
                $h .= "Return-Path: $from" . "\n";
                $h .= "Date: ".date("r")."\n";
                $h .= "MIME-Version: 1.0\n";
                $h .= "Content-type:text/html; charset=iso-8859-1 \n";
                $h .= "--{$mime_boundary}--";

                if ($isattached == "yes") {     
                $h .= "Content-Type: ".$ftype."; name=\"".basename($fileatt)."\"\r\n";
                $h .= "Content-Transfer-Encoding: base64\r\n";
                $h .= "Content-Disposition: attachment; filename=\"".basename($fileatt)."\"\r\n\r\n";
                $h .= $content."\r\n";
                $h .= "--{$mime_boundary}--";
                }

                // send mail
                if (mail($to, $subject, $messagehtml, $h))
                        $count++;
                    echo "Fileattname = ".$fileattname." | Inline = ".$inline."<br><br>";
                    }   
        echo "<div class=\"box green\"><center>$count Emails Sent.</center></div>";
    }
} else { ?>
        <form name='Sendhtml' action='' method='post' enctype='multipart/form-data'><br />
            Subject: <input id='subject' name='subject' /><br/><br/>
            Message: <br /><br /><textarea name="message" cols="40" rows="15"></textarea><br /><br />
            Include Image?<br /><br/><input type='file' name='file2' id='file2' /><br/><br/>
            Include Attachment?<br /><br /><input type='file' name='file' id='file' /><br/><br/>
            <input type='submit' name='submit' value='Submit' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type='reset' value='Reset' />
        </form>
<?php } ?>

I'm pretty sure the problem is with the headers ($h), but I'm not sure what. Please help.

Thank you in advance,

Robert

I would stick to my old advice use ... PHPMailer

Web Link : http://code.google.com/a/apache-extras.org/p/phpmailer/

Dowload Link : http://code.google.com/a/apache-extras.org/p/phpmailer/downloads/detail?name=PHPMailer_5.2.1.zip&can=2&q=

Sample Code

$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch

try {
  $mail->AddReplyTo('name@yourdomain.com', 'First Last');
  $mail->AddAddress('whoto@otherdomain.com', 'John Doe');
  $mail->SetFrom('name@yourdomain.com', 'First Last');
  $mail->AddReplyTo('name@yourdomain.com', 'First Last');
  $mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
  $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
  $mail->MsgHTML(file_get_contents('contents.html'));
  $mail->AddAttachment('images/phpmailer.gif');      // attachment
  $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
  $mail->Send();
  echo "Message Sent OK</p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}

Tested this code 20 times and it works perfectly fine ....

Thanks :)

=============== DISCARD OLD MESSAGE ============

You have some key header missing example :

$h.= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"\r\n\r\n";

Some of your headers are not also properly formatted i would advice you to use PHPMailer and if you want a simple send mail function you can use this one below ... (no validation included)

Well I got it to work, the headers were completely wrong of course, thank you all of you for your help. Incase anyone is needs it here is the new header and mail() section which works!

    //Setup Headers
    if ($isattached == "yes") {
        $ext = strrchr( $fileatt , '.');
        $ftype = "";
        if ($ext == ".doc") $ftype = "application/msword";
        if ($ext == ".jpg") $ftype = "image/jpeg";
        if ($ext == ".gif") $ftype = "image/gif";
        if ($ext == ".png") $ftype = "image/png";
        if ($ext == ".zip") $ftype = "application/zip";
        if ($ext == ".pdf") $ftype = "application/pdf";
        if ($ftype=="") $ftype = "application/octet-stream";

        // read file into $data var
        $file = fopen($fileatt, "rb");
        $data = fread($file,  filesize( $fileatt ) );
        fclose($file);

        // split the file into chunks for attaching
          $content = chunk_split(base64_encode($data));
     }
     $rand = md5( time() );  
     $mime_boundary = '==Multipart_Boundary_' . $rand;
     $h = "From: $name<$from>" . "\n";
     $h .="Reply-To: $from"."\n";
     $h .= "Return-Path: $from" . "\n"
     ."MIME-Version: 1.0\n" . 
     "Content-Type: multipart/mixed; boundary=\"" . $mime_boundary . "\""
     ."\n\n";
     $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" .
     $body . "\n\n";

     if ($content) {
        $message .= "--" . $mime_boundary . "\n" .
        "Content-Type: \"" . $ftype . "\";\n" .
        " name=\"" . basename($fileatt) . "\"\n" .
        "Content-Disposition: attachment;\n" .
        " filename=\"" . basename($fileatt) . "\"\n" .
        "Content-Transfer-Encoding: base64\n\n" .
        $content . "\n\n" .
        "--" . $mime_boundary . "--\n";
    }

    // send mail
    $sent = mail($to, $subject, $message, $h);
    $count++;  
    }    
    if ($sent) {
        echo "<div class=\"box green\"><center>$count Emails Sent.</center></div>"; 
    } else {
        echo "<div class=\"box red\"><center>$count Emails Sent.</center></div>"; 
    }
}

Thanks again for the help!

Robert

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM