Отправка электронной почты на странице контактов не работает - PullRequest
0 голосов
/ 06 августа 2011

Я использую следующий код, скопированный с веб-сайта, для страницы контактов.Но я не получаю никаких писем, и вложенные файлы не попадают в папку моего веб-сервера / var / www /.Я что-то здесь упускаю?

Я запускаю этот код на localhost.

email.php

ob_start();

$to = 'baltusaj@gmail.com';

/*$name = $_POST['name'];
$email = $_POST['email'];
$confirm_email = $_POST['confirm_email'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
$hidden = $_POST['hidden'];
$from = $email;
*/
$keys = array('name', 'email', 'confirm_email', 'subject', 'comments', 'hidden');
foreach($keys as $key)
{
    $$key = isset($_POST[$key]) ? $_POST[$key] : null ;
} 

print ('
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
     <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
       <title>Email</title>
<script type="text/javascript">
/*<![CDATA[*/
function progress(){
intWidth = parseInt(document.getElementById("container1").style.width) + 1;
if(intWidth <= 400){
     document.getElementById("container1").style.width = intWidth+"px";
}else{
     document.getElementById("container1").style.width = 0;
}
     setTimeout("progress()",300);
}
/*]]>*/
</script>
</head>

<body>
');

//Make sure email and confirm email are the same
if (!empty ($hidden)) {
    if ($email == $confirm_email) {
    }else{
    $email = '';
    $confirm_email = '';
    }
}


//Do a reg_ex check on the email
if (!empty ($hidden)) {    
   $regexp = "^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$";
   if (eregi($regexp, $email))
   {
   }else{
       $email = '';
    $confirm_email = '';
   }
}
// End of email checking




if (empty ($hidden)) {

print ('<div id="container2">
<h1 id="content_h1"><a name="text">    E-mail </a></h1> <p>Please use the following form to e-mail us:</p>

');

include ("form.php");    

print ('</div>

<div id="container0" style="display: none;">

<p style="font-size: 15pt; font-family: sans-serif; color:#fd6700; background:#fff;">
    Loading...
    </p>

<div id="container1" style="width:0px; height:5px; background-color:#fd6700; margin-top:0px; text-align: left;"></div>

<p>Please be patient while your data is processed. This may take a few moments especially if you are uploading a file.</p>

</div>
');

}

if (!empty ($hidden)) {

    if ($_FILES['fileatt']['error'] == 1){
        print ('<h1 id="content_h1"><a name="text">There has been an error</a></h1>  
                <p>The maximum file size that can be uploaded using this form is 2 megabytes.
                </p>');

    }elseif ( (!empty ($name)) && (!empty ($email)) && (!empty ($comments))&& (!empty ($subject))) {

    // Get html message content
$form_data = "<p>This email is from <span class=\"bold\">$name</span> \n\n ";
$form_data .= "<p>$comments</p>";

$message =         "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \n" .
                "    \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> \n" .
                "<html xmlns=\"http://www.w3.org/1999/xhtml\"> \n" .
                "<head> \n" .
                "  <meta http-equiv=\"content-type\" content= \n" .
                "  \"text/html; charset=iso-8859-1\" /> \n" .
                "<style type=\"text/css\"> \n" .
                "body {    font-size: 9pt; font-family:  verdana, sans-serif;     color: #000; background:#fff; }  \n" .
                ".bold { font-weight: bold; }  \n" .
                "</style>  \n" .
                "</head> \n" .
                "<body>$form_data \n" .
                "</body> \n" .
                "</html> \n\n";

// Obtain file upload vars
$fileatt      = $_FILES['fileatt']['tmp_name'];
$fileatt_type = $_FILES['fileatt']['type'];
$fileatt_name = $_FILES['fileatt']['name'];


$headers = "From: $from";

if (is_uploaded_file($fileatt)) {
// Read the file to be attached ('rb' = read binary)
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);

// Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

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

// Add a multipart boundary above the html message
$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";


// Base64 encode the file data
$data = chunk_split(base64_encode($data));

//We now have everything we need to write the portion of the message that contains the file attachment. Here's the code:

// Add file attachment to the message
$message .= "--{$mime_boundary}\n" .
             "Content-Type: {$fileatt_type};\n" .
             " name=\"{$fileatt_name}\"\n" .
             "Content-Disposition: attachment;\n" .
             " filename=\"{$fileatt_name}\"\n" .
             "Content-Transfer-Encoding: base64\n\n" .
             $data . "\n\n" .
             "--{$mime_boundary}--\n";
}else{
     // Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

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

// Add a multipart boundary above the html message
$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";
}                        


//That completes the modifications necessary to accommodate a file attachment. We can now send the message with a quick call to mail:

// Send the message
mail($to, $subject, $message, $headers);

$body = "Dear $name, \n\nThank you for your email. We will contact you as soon as possible regarding the matter. \n \n";

mail ($email, "Re: $subject", $body, 'From:you@your_email.com');

print ('<h1 id="content_h1"><a name="text">            Thank you             </a></h1> <p>We will contact you as soon as possible. You will receive an automatic e-mail immediately confirming the reception of your email.</p>');

}else{
    print ('<h1 id="content_h1"><a name="text">There has been an error</a></h1>  <p>Please fill in all the compulsory fields correctly and then resubmit the form. Thank you.</p>');
    include ("form.php");    
}
}

// This is the end of the insert

print ('

  </div>
</body>
</html>
');

ob_end_flush();

?> 

form.php

<div id="form">
        <form  action="email.php" enctype="multipart/form-data" method="post" onsubmit="
        document.getElementById('container0').style.display='';
        document.getElementById('container2').style.display='none';
        progress();
        return true;">
        <fieldset id="fieldset">
        <label for="name">Contact name<span style="color: red;">*</span>:</label>
        <input <?php if (!empty ($hidden)) { if (empty ($name)) { print 'style="background: pink;"'; } } ?> class="form_elements" id="name" type="text" name="name" value="<?php print "$name"; ?>" tabindex="1" />
        <br />
        <label for="email">E-mail address<span style="color: red;">*</span>:</label>
        <input <?php if (!empty ($hidden)) { if (empty ($email)) { print 'style="background: pink;"'; } } ?> class="form_elements" id="email" type="text" name="email" value="<?php print "$email"; ?>" tabindex="1" />
        <br />    
        <label for="confirm_email">Confirm e-mail<span style="color: red;">*</span>:</label>
        <input <?php if (!empty ($hidden)) { if (empty ($confirm_email)) { print 'style="background: pink;"'; } } ?> class="form_elements" id="confirm_email" type="text" name="confirm_email" value="<?php print "$confirm_email"; ?>" tabindex="1" />
        <br />    
        <label for="subject">Subject<span style="color: red;">*</span>:</label>
        <input <?php if (!empty ($hidden)) { if (empty ($subject)) { print 'style="background: pink;"'; } } ?> class="form_elements" id="subject" type="text" name="subject" value="<?php print "$subject"; ?>" tabindex="1" />
        <br />    
        <label for="comments">Comments<span style="color: red;">*</span>:</label>
        <textarea <?php if (!empty ($hidden)) { if (empty ($comments)) { print 'style="background: pink;"'; } } ?>class="form_elements" id="comments" name="comments" cols="19" rows="5" tabindex="1"><?php print "$comments"; ?></textarea>
        <br /><br />
        <label for="fileatt">Attach document:</label>
        <input id="fileatt" type="file" name="fileatt"  tabindex="1" />
        <br />
        <input  type="hidden" name="hidden"  value="1" /><br />
        <label for="submit"><span style="color: red;">*</span> Compulsory fields.</label>
        <input id="submit" type="submit" value="Send" tabindex="1" />
        </fieldset>
        </form>
        </div>

Ответы [ 2 ]

2 голосов
/ 06 августа 2011

Каджиллионный раз на этом сайте: не создавайте свои собственные сообщения пантомимы, это ненадежно и болезненно. Используйте взамен Swiftmailer или PHPMailer . Функция PHP mail () крайне ненадежна и не может произвести ЛЮБУЮ полезную диагностику того, почему что-то не получается. Swift / PHPMailer точно скажет вам, почему что-то взорвалось.

Кроме того, вы нигде не делаете move_uploaded_file(), поэтому ваши загруженные файлы будут автоматически удалены PHP при выходе из скрипта. Вы ДОЛЖНЫ иметь дело с файлами самостоятельно, а это значит, что вы должны написать код, чтобы переместить файлы в любое место, где вы хотите их хранить.

0 голосов
/ 06 августа 2011

Вы используете SMTP-сервер на своем локальном хосте?

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