【问题标题】:add file attachment php mail form添加文件附件php邮件表单
【发布时间】:2014-02-01 15:30:18
【问题描述】:

找人帮我做这件事。

我的网站上有一个邮件脚本,用于发送电子邮件,发送邮件工作正常,但我希望能够发送带附件的电子邮件,但这样做时遇到了问题。

这是表单的 php

<?php

// Set email variables
$email_to = 'youremail@address.com';
$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]+@([-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));
}

?>

【问题讨论】:

    标签: php forms email


    【解决方案1】:

    查看这个答案:Send attachments with PHP Mail()?

    我建议使用Swift mailer。我在使用它方面取得了非常好的成功。它不仅对附件有帮助,而且还允许您发送 HTML 电子邮件,而无需邮件程序将其发送到垃圾邮件。

    以下是 PHP 中普通邮件函数的一些代码:在发送带有附件的邮件下找到 here

    <?php 
    //define the receiver of the email 
    $to = 'youraddress@example.com'; 
    //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: webmaster@example.com\r\nReply-To: webmaster@example.com"; 
    //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"; 
    ?>
    

    【讨论】:

      【解决方案2】:

      假设你的表单有这个输入字段

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

      下面的函数将完成发送附件的工作,它需要参数$recipientEmail,$senderEmail, $subject,$message,只要您在提交表单时有上述输入字段,附件由$_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);
      
          }   
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-01
        • 2017-09-29
        • 2013-08-07
        • 1970-01-01
        • 2015-03-13
        相关资源
        最近更新 更多