2016-03-19 3 views
0

У меня возникли трудности с попыткой отладки моего кода php mail(). Я включил весь блок PHP ниже, поэтому, пожалуйста, простите форматирование и разделы, которые не актуальны (rCaptcha, проверка поля и т. Д.)php mail() функция вложение и тело оба пустые

Проблема, с которой я сталкиваюсь, заключается в том, что когда электронные письма проходят через ... 1) Там нет тела электронной почты ... и 2) Вложение пустое.

Если я прокомментирую эту строку «$ body. = $ My_attachment;» Я получаю ожидаемый текст в теле, и неудивительно, что нет привязанности.

Может ли кто-нибудь обнаружить мои, несомненно, новобрачные ошибки? Я ожидаю некоторые ответы, предлагающие использовать почтовую библиотеку PHP, которую я сейчас изучаю, но для моего понимания и образования я был бы признателен за конкретную обратную связь, указывающую на мои ошибки.

Благодарим за помощь.

<?php 
/******************************************** 
/Start processing the email 
/*******************************************/ 
# We'll make a list of error messages in an array 
$messages = array(); 
$upload_folder = "uploads/"; 
// a random hash will be necessary to send mixed content 
$separator = md5(time()); 

// carriage return type (we use a PHP end of line constant) 
$eol = PHP_EOL; 

// Change this to YOUR address 
$recipient = [email protected]>COM; 
$email = $_POST['myemail']; 
$phone = $_POST['phone']; 
$realName = $_POST['name']; 
$subject = "WEB CONTACT: Careers" ; 

$body = "--" . $separator . $eol; 
$body .= "FROM: " . $realName . 
     "\r\nPHONE: " . $phone . 
     "\r\nEMAIL: " . $email . 
     "\r\nCONTACT ME VIA: " . $_POST['contact_me'] . 
     "\r\nMESSAGE:" . $_POST['mymessage'] ; 

/******************************************** 
/ATTACHMENT 
/*******************************************/ 
//Get the uploaded file information 
$name_of_uploaded_file = 
    basename($_FILES['uploaded_file']['name']); 

//get the file extension of the file 
$type_of_uploaded_file = 
    substr($name_of_uploaded_file, 
    strrpos($name_of_uploaded_file, '.') + 1); 

$size_of_uploaded_file = 
    $_FILES["uploaded_file"]["size"]/1024;//size in KBs 

//Settings 
$max_allowed_file_size = 1024; // size in KB 
$allowed_extensions = array("pdf", "doc", "txt"); 

//Validations 
if($size_of_uploaded_file > $max_allowed_file_size) 
{ 
    $messages[] = "Size of file should be less than " . $max_allowed_file_size; 
} 

//------ Validate the file extension ----- 
$allowed_ext = false; 
for($i=0; $i<sizeof($allowed_extensions); $i++) 
{ 
    if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0) 
    { 
    $allowed_ext = true; 
    } 
} 

if(!$allowed_ext) 
{ 
    $messages[] = "The uploaded file is not supported file type. ". 
    " Only the following file types are supported: ".implode(',',$allowed_extensions); 
} 

//copy the temp. uploaded file to uploads folder 
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file; 
$tmp_path = $_FILES["uploaded_file"]["tmp_name"]; 

if(is_uploaded_file($tmp_path)) 
{ 
    if(!copy($tmp_path,$path_of_uploaded_file)) 
    { 
    $messages[] = 'Error while copying the uploaded file'; 
    } 
} 

// attachment 

    $file = $upload_folder . "/" . $name_of_uploaded_file; 
    $file_size = filesize($file); 
    $handle = fopen($file, "r"); 
    $content = fread($handle, $file_size); 
    fclose($handle); 
    $content = chunk_split(base64_encode($content)); 



/*********************************************************** 
// reCAPTCHA your recaptcha secret key 
***********************************************************/ 
$secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; 

if(isset($_POST['email'])) 
{ 
    $email=$_POST['email']; 
} 
if(isset($_POST['comment'])) 
{ 
    $email=$_POST['comment']; 
} 
if(isset($_POST['g-recaptcha-response'])) 
{ 
    $captcha=$_POST['g-recaptcha-response']; 
} 
     $ip = $_SERVER['REMOTE_ADDR']; 
     $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip); 
     $responseKeys = json_decode($response,true); 
     if(intval($responseKeys["success"]) !== 1) { 
      $messages[] = "The reCaptcha Question was not answered correctly. I am begining to suspect that you are a robot."; 
     } 
/*********************************************************** 
// END reCAPTCHA 
***********************************************************/   

/*********************************************************** 
// Message format validations 
***********************************************************/ 
# Allow only reasonable email addresses 
if (!preg_match("/^[\w\+\-.~]+\@[\-\w\.\!]+$/", $email)) { 
$messages[] = "That is not a valid email address."; 
} 
# Allow only reasonable real phone numbers 
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $phone)) { 
$messages[] = "The phone number must only include numbers, spaces, brackets(), and '+'."; 
} 
# Allow only reasonable real names 
if (!preg_match("/^[\w\ \+\-\'\"]+$/", $realName)) { 
$messages[] = "The real name field must contain only " . 
"alphabetical characters, numbers, spaces, and " . 
"reasonable punctuation. We apologize for any inconvenience."; 
} 
# CAREFUL: don't allow hackers to sneak line breaks and additional 
# headers into the message and trick us into spamming for them! 
$subject = preg_replace('/\s+/', ' ', $subject); 
# Make sure the subject isn't blank afterwards! 
if (preg_match('/^\s*$/', $subject)) { 
$messages[] = "Please choose area and office for your message."; 
} 

# Make sure the message has a body 
if (preg_match('/^\s*$/', $body)) { 
$messages[] = "Your message was blank. Did you mean to say " . 
"something?"; 
} 
    if (count($messages)) { 
    # There were problems, so tell the user and 
    # don't send the message yet 
    foreach ($messages as $message) { 
     echo("<p>$message</p>\n"); 
    } 
    echo("<p>Click the back button and correct the problems. " . 
     "Then click Send Your Message again.</p>"); 
    } 
    //else 
    { 
    # Send the email - we're done 


    // main header (multipart mandatory) 
    $headers = "From: " . $realName . $eol; 
    $headers .= "MIME-Version: 1.0" . $eol; 
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol; 
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol; 

    // message 
    $headers .= "--" . $separator . $eol; 
    $headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol; 
    $headers .= "Content-Transfer-Encoding: 8bit" . $eol; 
    $headers .= $body . $eol; 

    // attachment 
    $my_attachment =""; 
    $my_attachment .= "--" . $separator . $eol; 
    $my_attachment .= "Content-Type: application/octet-stream; name=\"" . $name_of_uploaded_file . "\"" . $eol; 
    $my_attachment .= "Content-Disposition: attachment; filename=\"" . $name_of_uploaded_file . "\"" . $eol; 
    $my_attachment .= "Content-Transfer-Encoding: base64" . $eol; 
    $my_attachment .= "Content-Disposition: attachment" . $eol; 
    $my_attachment .= $content . $eol; 
    $my_attachment .= "--" . $separator . "--"; 


    $body .= $my_attachment ; 



mail($recipient, 
     $subject, 
     $body, 
     $headers 
    ); 
    echo("<p>Your message has been sent. Thank you!</p>\n"); 
    } 
?> 
+0

Предлагаю вам использовать PhpMailer для отправки вложений, это проще, чем функция электронной почты(). https://github.com/PHPMailer/PHPMailer –

ответ

0

Вы можете использовать класс PHPmailer для отправки почты. Это очень простой вариант для отправки писем.

Использование PHPMailer:

  • Скачать PHPMailer сценарий здесь: http://github.com/PHPMailer/PHPMailer
  • Распакуйте архив и скопируйте папку скрипта в удобное место в вашем проекте.
  • Включите основной файл сценария - require_once('path/to/file/class.phpmailer.php');

Теперь, отправка электронной почты с вложениями идет от безумно трудно невероятно легко:

$email = new PHPMailer(); 
$email->From  = '[email protected]'; 

$email->FromName = 'Your Name'; 

$email->Subject = 'Message Subject'; 
$email->Body  = $bodytext; 
$email->AddAddress('[email protected]'); 

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE'; 

$email->AddAttachment($file_to_attach , 'NameOfFile.pdf'); 

return $email->Send(); 

Это просто одна строка $ email-> AddAttachment (); для добавления вложения.

+0

«Я ожидаю некоторых ответов, предлагающих использовать почтовую библиотеку PHP, которую я сейчас изучаю, но для моего понимания и образования я был бы признателен за конкретную обратную связь, указывающую на мои ошибки». – lmorse

Смежные вопросы