Попытка автоматически отправить встроенное и / или вложение с помощью mail () из HTML-формы, но продолжает получать двоичную строку - PullRequest
0 голосов
/ 28 марта 2012

Я пытаюсь создать форму электронной почты для клуба, который разрабатываю, и хочу, чтобы он проверил, добавляю ли я вложение или встроенное изображение в html-письмо. Пока все работает, за исключением случаев, когда я пытаюсь включить вложение, оно истекает через 90 секунд, и оно отправляет несколько электронных писем, а начало заполнено "---- Content-Type: application / pdf; name = «BrainMonkey-ooPic-RS.pdf» Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename = «test-RS.pdf», затем есть двоичная строка, представляющая файл, а в конце - html-электронная почта, которая была отправлено меньше вложение конечно. Вот код:

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

Я почти уверен, что проблема в заголовках ($ h), но я не уверен, что именно. Пожалуйста, помогите.

Заранее спасибо,

Роберт

Ответы [ 2 ]

0 голосов
/ 28 марта 2012

Ну, я заставил его работать, заголовки, конечно, были совершенно не правы, спасибо всем вам за вашу помощь.Если кому-то это нужно, вот новый заголовок и раздел mail (), который работает!

    //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>"; 
    }
}

Еще раз спасибо за помощь!

Роберт

0 голосов
/ 28 марта 2012

Я бы придерживался своего старого совета по использованию ... PHPMailer

Веб-ссылка: http://code.google.com/a/apache-extras.org/p/phpmailer/

Ссылка для скачивания: http://code.google.com/a/apache-extras.org/p/phpmailer/downloads/detail?name=PHPMailer_5.2.1.zip&can=2&q=

Пример кода

$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!
}

Протестировал этот код 20 раз, и он отлично работает ....

Спасибо :)

=============== ОТКЛОНИТЬ СТАРОЕ СООБЩЕНИЕ ============

У вас отсутствует пример заголовка ключа:

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

Некоторые из ваших заголовков также не отформатированы должным образом, я бы посоветовал вам использовать PHPMailer, и если вы хотите простую функцию отправки почты, вы можете использовать ее ниже ... (без проверки)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...