2015-02-17 3 views
-1

У меня есть php-код, работающий до такой степени, что мне нужно изображение, чтобы привязаться к переменной, и я получаю электронную почту с остальной частью моей формы. Я получаю 2 ошибки. Одна ошибка говорит мне, что $ messageImage в undefined в строке 75? а другой: вызов функции-члена addAttachment() для объекта без объекта в строке 75.Вложение загружается, но как мне отправить его по электронной почте?

может кто-то объяснить правильный способ объявления переменной и убедиться, что это объект, с которым работает addAttachment. Thank You

//copy the temp. uploaded file to uploads folder 
$upload_folder = 'uploads/'; 

$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)) 
    { 
    $errors = '\n error while copying the uploaded file'; 
    } 
} 



$to = "[email protected]"; // this is your Email address 
$from = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); // this is the sender's Email address 
$first_name = filter_var($_POST['first_name'], FILTER_SANITIZE_STRING); 
$story = filter_var($_POST['message'], FILTER_SANITIZE_STRING); 
$subject = "subject"; 
$subject2 = "Thank You for submitting"; 

$messageImage->addAttachment($path_of_uploaded_file); 


$message = $first_name . " wrote the following:" . "\n\n" . $story; 
$message2 = "Here is a copy of your story " . $first_name . "\n\n" . $story; 

$headers = "From:" . $from; 
$headers2 = "From:" . $to; 

mail($to,$subject,$message,$messageImage,$headers); 
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender 

ответ

0

«$ messageImage» - это объект в вашем коде, и он не определяется. Вы можете проверить это с помощью простой, если проверка, как показано ниже,

 if ($messageImage) { 
      // do something 
     } 

После кода может работать для вас,

 //copy the temp. uploaded file to uploads folder 
     $upload_folder = 'uploads/'; 

     $to = "[email protected]"; // this is your Email address 
     $from = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); // this is the sender's Email address 
     $first_name = filter_var($_POST['first_name'], FILTER_SANITIZE_STRING); 
     $story = filter_var($_POST['message'], FILTER_SANITIZE_STRING); 
     $subject = "subject"; 
     $subject2 = "Thank You for submitting"; 

     $message = $first_name . " wrote the following:" . "\n\n" . $story; 
     $message2 = "Here is a copy of your story " . $first_name . "\n\n" . $story; 

     $headers = "From: $from"; 
     // 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/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; 
     $message .= "--{$mime_boundary}\n"; 

     $content = ''; 
     $tmp_path = $_FILES["uploaded_file"]["tmp_name"]; 
     if($tmp_path) { 
        $filename = $_FILES["uploaded_file"]["name"]; 
        $path_of_uploaded_file = $upload_folder . $filename; 
        if(!copy($tmp_path, $path_of_uploaded_file)) 
        { 
            $errors = '\n error while copying the uploaded file'; 
        } 
        $file_size = filesize($path_of_uploaded_file); 
        $handle = fopen($path_of_uploaded_file, "rb"); 
        $content = fread($handle, $file_size); 
        fclose($handle); 
        $content = chunk_split(base64_encode($content)); 
      } 

     // if attachment 
     if ($content) { 
     $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"{$filename}\"\n" . 
"Content-Disposition: attachment;\n" . " filename=\"{$filename}\"\n" . 
"Content-Transfer-Encoding: base64\n\n" . $content . "\n\n"; 
$message .= "--{$mime_boundary}\n"; 
     } 
     $headers2 = "From:" . $to; 

     mail($to, $subject, $message, $headers); 
     mail($from, $subject2, $message2, $headers2); // sends a copy of the message to the sender 
+0

Вы, сэр, гений. Большое спасибо, я попробовал код, и он работает! но теперь я собираюсь идти по очереди, чтобы посмотреть, как все работает. еще раз спасибо – gio

0

В вашем коде $ messageImage не установлен. Поскольку он не установлен, он равен NULL, вызывая следующую ошибку, вы пытаетесь обратиться к методу объекта, но это значение равно null.

Чтобы отправить сообщение с прикрепленными файлами, вам необходимо установить заголовки электронной почты, и изображение будет закодировано в коде base64. Я хотел бы посмотреть на этот другой StackOverflow ответ:

https://stackoverflow.com/a/17371739/2832264

Чтобы сделать простой объект:

$obj = new stdClass(); 

В противном случае, вы можете создать класс, убедитесь, что он включен в сценарии, а также создавать новый пример:

$obj = new Person(); 

Я читал официальную документацию PHP по классам.

+0

ах ок спасибо за разработку немного больше, что я должен делать. – gio

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