2014-02-01 6 views
0

ищет кого-то, чтобы помочь мне сделать это.добавить файл вложение php mail form

У меня на моем сайте есть почтовый скрипт, который я использую для отправки писем, отправляющих почту, но я хочу, чтобы иметь возможность отправлять электронное письмо с вложениями, и у меня возникают проблемы с этим.

здесь является PHP для формы

<?php 

// Set email variables 
$email_to = '[email protected]'; 
$email_subject = 'Form submission'; 

// Set required fields 
$required_fields = array('fullname','email','comment'); 

// set error messages 
$error_messages = array(
'fullname' => 'Please enter a Name to proceed.', 
'email' => 'Please enter a valid Email Address to continue.', 
'comment' => 'Please enter your Message to continue.' 
); 

// Set form status 
$form_complete = FALSE; 

// configure validation array 
$validation = array(); 

// check form submittal 
if(!empty($_POST)) { 
// Sanitise POST array 
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value)); 

// Loop into required fields and make sure they match our needs 
foreach($required_fields as $field) {  
    // the field has been submitted? 
    if(!array_key_exists($field, $_POST)) array_push($validation, $field); 

    // check there is information in the field? 
    if($_POST[$field] == '') array_push($validation, $field); 

    // validate the email address supplied 
    if($field == 'email') if(!validate_email_address($_POST[$field]))array_push $validation, $field); 
} 

// basic validation result 
if(count($validation) == 0) { 
    // Prepare our content string 
    $email_content = 'New Website Comment: ' . "\n\n"; 

    // simple email content 
    foreach($_POST as $key => $value) { 
     if($key != 'submit') $email_content .= $key . ': ' . $value . "\n"; 
    } 

    // if validation passed ok then send the email 
    mail($email_to, $email_subject, $email_content); 

    // Update form switch 
    $form_complete = TRUE; 
} 
} 

function validate_email_address($email = FALSE) { 
return (preg_match('/^[^@\s][email protected]([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE; 
} 

function remove_email_injection($field = FALSE) { 
    return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-  Type:", "bcc:","to:","cc:"), '', $field)); 
} 

?> 

ответ

0

Проверить этот ответ из: Send attachments with PHP Mail()?

Я рекомендую использовать Swift mailer. Я использовал ОЧЕНЬ хороший успех. Это не только помогает вложениях, но также позволяет отправлять HTML-письма без почтовых программ, отправляя их спаму.

Ниже приведен код для функции обычной почты в PHP: найдено here Под почтой отправки с прикрепленными файлами.

<?php 
//define the receiver of the email 
$to = '[email protected]'; 
//define the subject of the email 
$subject = 'Test email with attachment'; 
//create a boundary string. It must be unique 
//so we use the MD5 algorithm to generate a random hash 
$random_hash = md5(date('r', time())); 
//define the headers we want passed. Note that they are separated with \r\n 
$headers = "From: [email protected]\r\nReply-To: [email protected]"; 
//add boundary string and mime type specification 
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; 
//read the atachment file contents into a string, 
//encode it with MIME base64, 
//and split it into smaller chunks 
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip'))); 
//define the body of the message. 
ob_start(); //Turn on output buffering 
?> 
--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" 

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit 

Hello World!!! 
This is simple text email message. 

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/html; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit 

<h2>Hello World!</h2> 
<p>This is something with <b>HTML</b> formatting.</p> 

--PHP-alt-<?php echo $random_hash; ?>-- 

--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: application/zip; name="attachment.zip" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

<?php echo $attachment; ?> 
--PHP-mixed-<?php echo $random_hash; ?>-- 

<?php 
//copy current buffer contents into $message variable and delete current output buffer 
$message = ob_get_clean(); 
//send the email 
$mail_sent = @mail($to, $subject, $message, $headers); 
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed"; 
?> 
0

Предположим, ваш вид имеет это поле ввода

<label for="Attachment">Attachment:</label> 
<input type="file" name="attach1" id="attach1" /> 

Функция ниже будет делать работу для отправки вложения, он принимает параметры $ recipientEmail, $ SENDEREMAIL, $ предметные, $ сообщение, вложение позаботится $ _FILE, если у вас есть указанное поле ввода при отправке формы.

public function sendEmailWithAttachments($recipientEmail,$senderEmail, $subject,$message){ 
    if(isset($_FILES) && (bool) $_FILES) { 

     $allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","JPG","png","PNG","rtf","txt","xml"); 

     $files = array(); 
     foreach($_FILES as $name=>$file) { 
      //die("file size: ".$file['size']); 
      if($file['size']>=5242880)//5mb 
      { 
       $fileSize=$file['size']; 
       return false; 
      } 
      $file_name = $file['name']; 
      $temp_name = $file['tmp_name']; 
      $file_type = $file['type']; 
      $path_parts = pathinfo($file_name); 
      $ext = $path_parts['extension']; 
      if(!in_array($ext,$allowedExtensions)) { 
       return false; 
       //die("File $file_name has the extensions $ext which is not allowed"); 
      } 

      //move the file to the server, cannot be skipped 
      $server_file="/tmp/$path_parts[basename]"; 
      move_uploaded_file($temp_name,$server_file); 
      array_push($files,$server_file); 
      //array_push($files,$temp_name); 
     } 

     // email fields 
     $headers = "From: $senderEmail"; 


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

     // preparing attachments 
     for($x=0;$x<count($files);$x++){ 
      $file = fopen($files[$x],"rb"); 
      $data = fread($file,filesize($files[$x])); 
      fclose($file); 
      $data = chunk_split(base64_encode($data)); 
      $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . 
      "Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" . 
      "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; 
      $message .= "--{$mime_boundary}\n"; 
     } 

     // send 
     return @mail($recipientEmail, $subject, $message, $headers); 

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