将文件附加到PHP联系表单

时间:2017-04-02 11:24:59

标签: php email-attachments

我已经用html创建了一个联系人并使用PHP代码将它发送给我的电子邮件并且工作正常但我有一个问题,我想附加文件并被发送但我不知道怎么这样任何人都可以帮助我...和PHP代码下面只是想添加文件的附件 提前谢谢

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>

<!-- Start PHP CODE -->
<?php
error_reporting(E_ALL);
 ini_set('display_errors', 1);
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = $result =  "" ;
if(isset($_POST['submit']))
{
// define contact form variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$design = $_POST['design'];
$country = $_POST['country'];
$comment = $_POST['comment'];
$human = $_POST['human'];
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = "" ;
// define Checks variables
$check1 = $check2 = $check3  = $check4 = "";
// define email variables
$to = 'eng.bolaraafat@gmail.com';
$subject = 'Contact Form';
$message = 'From: '.$fname .$lname."\r\n".
           'E-mail: '.$email."\r\n".
           'Telephone: '.$tel."\r\n".
           'Designation: '.$design."\r\n".
           'Country Appled From: '.$country."\r\n".
           'Message: '.$comment."\r\n";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers = "From:" .$email. "\n" ;	
	
// Let's do some checks	
// Checking the First Name
if(empty($_POST["fname"])){
	$fnameErr = "Name is Required";
}else{
	$fname = test_input($_POST["fname"]);
	// check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
      $fnameErr = "Only letters and white space allowed"; 
    }else{
		$check1 = 1;
	}
}
// Checking the Last Name	
if(empty($_POST["lname"])){
	$lnameErr = "Name is Required";
}else{
	$lname = test_input($_POST["lname"]);
	// check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
      $lnameErr = "Only letters and white space allowed"; 
    }else{
		$check2 = 1;
	}
}
//Checking the Email Adress
if(empty($_POST["email"])){
	$emailErr = "Email is Required";
}else{
	$email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }else{
		$check3 = 1;
	}
}
//Checking the Anti-Spam Question
if(empty($_POST["human"])){
	$humanErr = "Please Enter the Answer";
}else{
	if ($human != 4){
		$humanErr = "Please check your answer";
	}else{
		$check4 = 1;
	}
}
	
// Emailing the Contents if all Checks are correct	
if($check1 && $check2 && $check3 && $check4 == 1){
	mail($to, $subject, $message, $headers);
	$result =  "Message Sent Sucessfully";
}else{
	$result = "Message Can't be sent";
}
} 
 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>
<!-- END OF PHP CODE --> 


<h2>Contact Form</h2>
<p><span style="color: red" >*Required field</span></p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
	First Name:<input type="text" name="fname"><span style="color: red" >*</span>  <?php echo $fnameErr ?> <br><br>
	Last Name:<input type="text" name="lname"><span style="color: red" >*</span> <?php echo $lnameErr ?> <br><br>
	E-mail:<input type="text" name="email"><span style="color: red" >*</span> <?php echo $emailErr ?> <br><br>
	Telephone:<input type="text" name="tel"><br><br>
	Designation:<select name="design">
  		<option value="Architectural Engineer">Architectural Engineer</option>
  		<option value="Structural Engineer">Structural Engineer</option>
  		<option value="Draughts-man">Draughts-man</option>
  		<option value="Receptionist">Receptionist</option>
  		<option value="Secertary">Secertary</option>
	  </select><br><br>
	  Country Applied From:<select name="country">
		<option value="">Country...</option>
		<option value="Afganistan">Afghanistan</option>
		<option value="Albania">Albania</option>
</select><br><br>
	Message:<textarea name="comment"></textarea> <br><br>
	Upload Your Resume:<span style="color: red" >*</span><input type="file" name="uploaded_file"><br><br>	
	<label>*What is 2+2? (Anti-spam)</label>
	<input name="human" placeholder="Type Here"><span style="color: red" >*</span><?php echo $humanErr ?><br><br>
	<input type="submit" name="submit" value="Submit">
	<input type="reset" value="Clear">
<?php echo $result ?>
</form><br>

</body>
</html>

1 个答案:

答案 0 :(得分:3)

您可以使用PHPMailer库轻松发送带附件的电子邮件

$email = new PHPMailer();
$email->From      = 'fromemail@domain.com';
$email->FromName  = 'From Name';
$email->Subject   = 'Your Email Subject';
$email->Body      = $bodytext;
$email->AddAddress( 'toemail@gmail.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

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

return $email->Send();

确保包含PHPMailer库。您可以从此处获取此库(https://github.com/PHPMailer/PHPMailer

根据评论请求,添加上传代码和电子邮件代码,完整示例如下:

<?php
error_reporting(E_ALL);
 ini_set('display_errors', 1);
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = $result =  "" ;
if(isset($_POST['submit']))
{
//checking attached file and uploading it to folder
$upload_file_path = '';
if (isset($_FILES['uploaded_file']) && !empty($_FILES['uploaded_file']))    
{
    $dir_path = getcwd();//getting current working directory path
    $upload_dir = $dir_path . 'uploads/';
    if (!file_exists($upload_dir))
    {
        mkdir($upload_dir, 0777, true);
    }
    $file_name = $_FILES['uploaded_file']['name'];
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);

    //validating uploaded file extension
    $valid_extensions = array('pdf', 'doc');//You can customize extension's here

    if (!in_array($ext, $valid_extensions))
    {
        exit('Please use .pdf or .doc file to upload CV.');
    }
    $upload_file_path = $upload_dir . $file_name;

    move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $upload_file_path);    

}


// Let's do some checks 
// Checking the First Name
if(empty($_POST["fname"])){
    $fnameErr = "Name is Required";
}else{
    $fname = test_input($_POST["fname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
      $fnameErr = "Only letters and white space allowed"; 
    }else{
        $check1 = 1;
    }
}
// Checking the Last Name   
if(empty($_POST["lname"])){
    $lnameErr = "Name is Required";
}else{
    $lname = test_input($_POST["lname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
      $lnameErr = "Only letters and white space allowed"; 
    }else{
        $check2 = 1;
    }
}
//Checking the Email Adress
if(empty($_POST["email"])){
    $emailErr = "Email is Required";
}else{
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }else{
        $check3 = 1;
    }
}
//Checking the Anti-Spam Question
if(empty($_POST["human"])){
    $humanErr = "Please Enter the Answer";
}else{
    if ($human != 4){
        $humanErr = "Please check your answer";
    }else{
        $check4 = 1;
    }
}

// Emailing the Contents if all Checks are correct  
if($check1 && $check2 && $check3 && $check4 == 1){
    mail($to, $subject, $message, $headers);
    $result =  "Message Sent Sucessfully";
}else{
    $result = "Message Can't be sent";
}
} 
 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

// define contact form variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$design = $_POST['design'];
$country = $_POST['country'];
$comment = $_POST['comment'];
$human = $_POST['human'];
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = "" ;
// define Checks variables
$check1 = $check2 = $check3  = $check4 = "";
// define email variables
$to = 'eng.bolaraafat@gmail.com';
$subject = 'Contact Form';
$message = 'From: '.$fname .$lname."\r\n".
           'E-mail: '.$email."\r\n".
           'Telephone: '.$tel."\r\n".
           'Designation: '.$design."\r\n".
           'Country Appled From: '.$country."\r\n".
           'Message: '.$comment."\r\n";

$email = new PHPMailer();
$email->From      = 'fromemail@domain.com';//Your From Email
$email->FromName  = $fname;
$email->Subject   = $subject;
$email->Body      = $message;
$email->AddAddress( $email );

if (!empty($upload_file_path))
{
    $email->AddAttachment( $upload_file_path , 'CV_'.time().'.pdf' );
}

return $email->Send();



?>

试试这个,如果您有任何问题,请告诉我。另外,请确保在php文件的顶部包含phpmailer库。