php电子邮件表单附件错误

时间:2016-01-16 16:57:26

标签: php attachment email-attachments

所以我有一个php文件,它从我的表单发送信息以及指定电子邮件地址的附件。一切正常,但当文件以电子邮件形式到达时,附件无法正常工作并显示错误的文件类型。我还在学习php。任何指导都会有所帮助。

这是php代码。

<?php 
//Keep people happy, send email by state
$firstbdestates = array("CT", "DE", "ME", "MA", "MD", "NH", "NJ", "NY", "PA", "RI", "WV", "VT", "VA"); 
$secondbdestates = array("AL", "GA", "FL", "MS", "NC", "PR", "SC", "TN");
$thirdbdestates = array("IN", "IL", "IA", "KY", "MI", "MN", "ND", "NE", "OH", "SD", "WI");
$fourthbdestates = array("AZ", "AR", "CO", "KS", "LA", "MO", "NM", "OK", "TX");
$fifthbdestates = array("AK", "CA", "HI", "ID", "MT", "NV", "OR", "UT", "WA", "WY");
$test = array("test"); //test email so I don't piss off BDE CO's
// died and error are interchangeable names, anything listed as "died" will display on  generated page.
function died($error) {
    echo "We are very sorry, but there were error(s) found with the form you submitted. ";
    echo "These errors appear below.<br /><br />";
    echo $error."<br /><br />";
    echo "Please use your back button to go  back and fix these errors.<br /><br />";
    die();
}
// Backasswords validation.  All data listed here in '' will trigger  error if not filled out in its entirety.
if(!isset($_POST['mname']) || //A-Za-z- only
!isset($_POST['telephone']) ||
!isset($_POST['email']) ||
!isset($_POST['streetline1']) ||
!isset($_POST['towncity']) || //A-Za-z- only
!isset($_POST['state']) ||
!isset($_POST['zip']) ||
!isset($_POST['dob']) ||
!isset($_POST['servicebranch']) ||
!isset($_POST['discharge']) ||
!isset($_POST['ratemos']) ||
!isset($_POST['yearsservice']) ||
!isset($_POST['econtactname']) || //A-Za-z- only
!isset($_POST['econtactnumber'])  ||
!isset($_POST['ndaagree']) ||
!isset($_POST['username']) ||
!isset($_POST['password']) ||
!isset($_POST['tosagree']) ||
!isset($_POST['wolagree'])) {
died('<span style="color:#ff0000">One or more fields were not filled out.</span>');       
}
//email validation
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
 if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
 }
// Simple sanitization for unwanted characters A-Za-z- only
$string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$mname)) {
    $error_message .= 'The name you entered does not appear to be valid.<br />';
   }
$string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$towncity)) {
    $error_message .= 'The town or city you entered does not appear to be valid.<br />';
   }
$string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$econtactname)) {
    $error_message .= 'The emergency contact name you entered does not appear to be valid.<br />';
   }

// Callout all form data...WHAT A BITCH!
$mname = $_POST['mname']; // required
$telephone = $_POST['telephone']; // required
$email = $_POST['email']; // required
$streetline1 = $_POST['streetline1']; // required
$streetline2 = $_POST['streetline2']; // required
$towncity = $_POST['towncity']; // required
$state = $_POST['state']; // required
$zip = $_POST['zip']; // required
$dob = $_POST['dob']; // required
$servicebranch = $_POST['servicebranch']; // required
$discharge = $_POST['discharge']; // required
$ratemos = $_POST['ratemos']; // required
$yearsservice = $_POST['yearsservice']; // required
$econtactname = $_POST['econtactname']; // required
$econtactnumber = $_POST['econtactnumber']; // required
$ndaagree = $_POST['ndaagree']; // required
$username = $_POST['username']; // required
$password = $_POST['password']; // required
$tosagree = $_POST['tosagree']; // required
$wolagree = $_POST['wolagree']; // required
//
//
//callout for error message
$error_message = "";
//Turn on error reporting so I can see what I screw up
error_reporting(E_ALL);
ini_set('display_errors', 1);
// FIle Upload to server---Then pull from server
if(isset($_FILES) && (bool) $_FILES) {
    $allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt"); // Allowed file types
    $files = array();
    foreach($_FILES as $name=>$file) {
        $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)) {
            die("Either you did not select a file or it is an incorrect file type.  Please try again.");
        }
        array_push($files,$file);
    }
    //If NO ERRORS, proceed
    // email fields: to, from, subject, and so on and so on.  Format pretty so people smile
    $to = myFunction();
    $from = "webmaster@warriorpointe.org"; 
    $subject ="$mname has requested to Join";
    $message = "<span style='color:#ff0000';>*** This email contains sensitive member information ***</span><br />
                Greetings BDE CO, <br />
                Today, $mname has requested to join Warrior Pointe and they are within your brigade limits. You are receiving this message because they are assigned. Please ensure that you set up the members forum account.  If you are unable to, please notify Patrick or Robert and they can build it for you.<br />
                <span style='color:#ff0000'>*** This email contains sensitive member information ***</span><br /><br /><br />
                ";
    // Geek Translator - all this crap in English so I don't get yelled at
    $message .="Members Name: ".clean_string($mname)."\n <br /> Contact Number: ".clean_string($telephone)."\n <br /> Email: ".clean_string($email)."\n <br /> Street Address: ".clean_string($streetline1)."\n <br /> Street Address 2: ".clean_string($streetline2)."\n <br /> Town or City: ".clean_string($towncity)."\n <br /> State: ".clean_string($state)."\n <br /> Zip Code: ".clean_string($zip)."\n <br /> Date of Birth: ".clean_string($dob)."\n <br /> Branch of Service: ".clean_string($servicebranch)."\n <br /> Discharge Status: ".clean_string($discharge)."\n <br /> Rate or MOS: ".clean_string($ratemos)."\n <br /> Years of Service: ".clean_string($yearsservice)."\n <br /> Emergency Contact Name: ".clean_string($econtactname)."\n <br /> Emergency Contact Number: ".clean_string($econtactnumber)."\n <br /> NDA Agreement: ".clean_string($ndaagree)."\n <br /> Waiver of Liability: ".clean_string($wolagree)."\n <br /> Forum TOS Agree: ".clean_string($tosagree)."\n <br /> Forum User Name: ".clean_string($username)."\n <br /> Forum Password: ".clean_string($password)."\n <br />"; 
    $message .="<span style='color:#ff0000'>*** END OF MESSAGE ***</span>";
    // Tell them who the message is from
    $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/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 8bit\n\n" . $message . "\n\n"; 
    $message .= "--{$mime_boundary}\n"; 
    // preparing attachments
    for($x=0;$x<count($files);$x++){
        $file = fopen($files[$x]['tmp_name'],"rb");
        $data = fread($file,filesize($files[$x]['tmp_name']));
        fclose($file);
        $data = chunk_split(base64_encode($data));
        $name = $files[$x]['name'];
        $message .= "Content-Type: {$fileType};\n" . " name=\"$name\"\n" . 
        "Content-Disposition: attachment;\n" . " filename=\"$name\"\n" . 
        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
        $message .= "--{$mime_boundary}\n";
    }
    // send the form Jeeves 
    $ok = mail($to, $subject, $message, $headers); 
    if ($ok) { 
         echo "<img src='images/png/apple-touch-icon-128.png'><br />Thank you for registering with Warrior Pointe.  You registration form has already been forwarded to the correct brigade staff for processing.  Typical processing time is no more than 72 hours.  If you have not heard form brigade staff within 72 hours, please email webmaster@warriorpointe.org.<br/><br/>";
                } else {
                    echo '<div style="color: red">' . $errors . '<br/></div>';
                }
    }
// This is how the dang sender knows who to mail too.
function myFunction() {
    if (in_array($_POST['state'], $GLOBALS["firstbdestates"])) {
        return "1stbdecommander@warriorpointe.org, hr@warriorpointe.org, webmaster@warriorpointe.org, archive@warriorpointe.org";
    } 
    else if (in_array($_POST['state'], $GLOBALS["secondbdestates"])) {
        return "2ndbdecommander@warriorpointe.org, hr@warriorpointe.org, webmaster@warriorpointe.org, archive@warriorpointe.org";
    } 
    else if (in_array($_POST['state'], $GLOBALS["thirdbdestates"])) {
        return "3rdbdecommander@warriorpointe.org, hr@warriorpointe.org, webmaster@warriorpointe.org, archive@warriorpointe.org"; 
    } 
    else if (in_array($_POST['state'], $GLOBALS["fourthbdestates"])) {
     return "4thbdecommander@warriorpointe.org, hr@warriorpointe.org, webmaster@warriorpointe.org, archive@warriorpointe.org";
    } 
    else if (in_array($_POST['state'], $GLOBALS["fifthbdestates"])) {
        return "5thbdecommander@warriorpointe.org, hr@warriorpointe.org, webmaster@warriorpointe.org, archive@warriorpointe.org "; 
    }
    else if (in_array($_POST['state'], $GLOBALS["test"])) {
        return "webmaster@warriorpointe.org";
    } 
    else {
        return "president@warriorpointe.org, webmaster@warriorpointe.org, 

archive@warriorpointe.org";
        }

}
function clean_string($string) {
    $bad = array("content-type","bcc:","to:","cc:","href");
    return str_replace($bad,"",$string);}
?>`

1 个答案:

答案 0 :(得分:0)

您可以使用这样的php邮件程序类发送附件

这是班级https://github.com/PHPMailer/PHPMailer/blob/master/class.phpmailer.php

以下是如何发送附件的代码

$mail = new PHPMailer(); // defaults to using php "mail()"
        $mail->SetFrom('abc@abc.com', 'abc@abc.com');
        $address = 'xyz@xyz.com';
        $mail->Subject = 'test';
        $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional

        $mail->MsgHTML('this is test message');
        $mail->isHTML(true);

        $mail->AddAttachment("images/logo1.png"); // attachment
        $mail->AddAttachment("images/engr mudasir.jpg"); // attachment

        if(!$mail->Send()) {
            echo $output = $mail->ErrorInfo;
        } else {
            echo $output = 'thank you';
        }