Jump to content

Uploading file and sending as attachment in e-mail


ayushkhemka

Recommended Posts

I want to create a form where you can upload a file and that can be sent as an attachment of an e-mail.
 
I've have two alternatives, one using PHPMailer, and the other not using PHPMailer.
 
My problems are as listed:
 
 1. When using PHPMailer, I'm getting the `SMTP:Could Not Connect()` error even though all the SMTP credentials are right.
 2. When not using PHPMailer, I'm getting an error in the `fopen()` function. Even then, I'm receiving the file, but its empty.
 
I'm really a starter with PHP, so need help on this one. I'm posting both the codes here.
 
1. Using PHPMailer:
 
       
<?php
    
    require('PHPMailer/class.phpmailer.php');
    
    if(isset($_POST['email'])) {
         
        // EDIT THE 2 LINES BELOW AS REQUIRED
        //$email_to = "email";
        //$email_subject = "Request for Portfolio check up from ".$first_name." ".$last_name;
     
     $title = array('Title', 'Mr.', 'Ms.', 'Mrs.');
     $selected_key = $_POST['title'];
     $selected_val = $title[$_POST['title']]; 
        
        $first_name = $_POST['first_name']; // required
        $last_name = $_POST['last_name']; // required
        $email_from = $_POST['email']; // required
        $telephone = $_POST['telephone']; // not required
        $comments = $_POST['comments']; // required
     
      if(($selected_key==0))
       echo "<script> alert('Please enter your title')</script>";
     function clean_string($string) {
          $bad = array("content-type","bcc:","to:","cc:","href");
          return str_replace($bad,"",$string);
        }
      $email_message = "";
     $email_message .="Title: ".$selected_val."\n";
     $email_message .= "First Name: ".clean_string($first_name)."\n";
        $email_message .= "Last Name: ".clean_string($last_name)."\n";
        $email_message .= "Email: ".clean_string($email_from)."\n";
        $email_message .= "Telephone: ".clean_string($telephone)."\n";
        $email_message .= "Comments: ".clean_string($comments)."\n";
    
     $allowedExts = array("doc", "docx", "xls", "xlsx", "pdf");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);
    if ((($_FILES["file"]["type"] == "application/pdf")
    || ($_FILES["file"]["type"] == "application/msword")
    || ($_FILES["file"]["type"] == "application/excel")
    || ($_FILES["file"]["type"] == "application/vnd.ms-excel")
    || ($_FILES["file"]["type"] == "application/x-excel")
    || ($_FILES["file"]["type"] == "application/x-msexcel")
    || ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
    || ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
    
    && in_array($extension, $allowedExts))
      {
      if ($_FILES["file"]["error"] > 0)
        {
        echo "<script>alert('Error: " . $_FILES["file"]["error"] ."')</script>";
        }
      else
        {
        if(move_uploaded_file($_FILES["file"]["tmp_name"],
          "upload/" . $_FILES["file"]["name"]))
       $file=fopen("upload/".$_FILES["file"]["name"], 'r');
        }
      }
    else
      {
      echo "<script>alert('Invalid file')</script>";
      }
         
    // create email headers
    $headers = 'From: '.$email_from."\r\n".
    'Reply-To: '.$email_from."\r\n" .
    'X-Mailer: PHP/' . phpversion();
    //Create a new PHPMailer instance
    $mail = new PHPMailer();
    //Tell PHPMailer to use SMTP
    $mail->IsSMTP();
    //Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $mail->SMTPDebug  = 2;
    //Ask for HTML-friendly debug output
    $mail->Debugoutput = 'html';
    //Set the hostname of the mail server
    $mail->Host       = "hostname";
    //Set the SMTP port number - likely to be 25, 465 or 587
    $mail->Port       = 465;
    //Whether to use SMTP authentication
    $mail->SMTPAuth   = true;
    //Username to use for SMTP authentication
    $mail->Username   = "email";
    //Password to use for SMTP authentication
    $mail->Password   = "password";
    //Set who the message is to be sent from
    $mail->SetFrom($email_from, 'First Last');
    //Set an alternative reply-to address
    //$mail->AddReplyTo('replyto@example.com','First Last');
    //Set who the message is to be sent to
    $mail->AddAddress('email', 'name');
    //Set the subject line
    $mail->Subject = 'Request for Profile Check up';
    //Read an HTML message body from an external file, convert referenced images to embedded, convert HTML into a basic plain-text alternative body
    $mail->MsgHTML($email_message);
    //Replace the plain text body with one created manually
    $mail->AltBody = 'This is a plain-text message body';
    //Attach an image file
    $mail->AddAttachment($file);
    
    //Send the message, check for errors
    if(!$mail->Send()) {
      echo "<script>alert('Mailer Error: " . $mail->ErrorInfo."')</script>";
    } else {
      echo "<script>alert('Your request has been submitted. We will contact you soon.')</script>";
    }
    }

?>

 

 

2. No PHPMailer:
 
 

    <?php
        
        $title = array('Title', 'Mr.', 'Ms.', 'Mrs.');
         $selected_key = $_POST['title'];
         $selected_val = $title[$_POST['title']]; 
            
            $first_name = $_POST['first_name']; // required
            $last_name = $_POST['last_name']; // required
            $email_from = $_POST['email']; // required
            $telephone = $_POST['telephone']; // not required
            $comments = $_POST['comments']; // required
         
            if(($selected_key==0))
           echo "<script> alert('Please enter your title')</script>";
         function clean_string($string) {
              $bad = array("content-type","bcc:","to:","cc:","href");
              return str_replace($bad,"",$string);
            }
          $email_message = "";
         $email_message .="Title: ".$selected_val."\n";
         $email_message .= "First Name: ".clean_string($first_name)."\n";
            $email_message .= "Last Name: ".clean_string($last_name)."\n";
            $email_message .= "Email: ".clean_string($email_from)."\n";
            $email_message .= "Telephone: ".clean_string($telephone)."\n";
            $email_message .= "Comments: ".clean_string($comments)."\n";
         
        $email_to = "email"; // The email you are sending to (example)
        //$email_from = "sendfrom@email.com"; // The email you are sending from (example)
        $email_subject = "subject line"; // The Subject of the email
        //$email_txt = "text body of message"; // Message that the email has in it
        $destination=$_FILES["file"]["name"];
        move_uploaded_file($_FILES["file"]["name"], $destination);
        $fileatt = fopen($_FILES['file']['name'],'r'); // Path to the file (example)
        $fileatt_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; // File Type
        $fileatt_name = "Details.docx"; // Filename that will be used for the file as the attachment
        $file = fopen($fileatt,'r');
        $data = fread($file,filesize($fileatt));
        fclose($file);
        $semi_rand = md5(time());
        $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
        $headers="From: $email_from"; // Who the email is from (example)
        $headers .= "\nMIME-Version: 1.0\n" .
        "Content-Type: multipart/mixed;\n" .
        " boundary=\"{$mime_boundary}\"";
        $email_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: 7bit\n\n" . $email_txt;
        $email_message .= "\n\n";
        $data = chunk_split(base64_encode($data));
        $email_message .= "--{$mime_boundary}\n" .
        "Content-Type: {$fileatt_type};\n" .
        " name=\"{$fileatt_name}\"\n" .
        "Content-Transfer-Encoding: base64\n\n" .
        $data . "\n\n" .
        "--{$mime_boundary}--\n";
        
        mail($email_to,$email_subject,$email_message,$headers);
        ?>

And the form, with corresponding action:
 <form name="contactform" method="post" action="send2.php" enctype="multipart/form-data">
    <table width="100%" border="0" align="center">
    <tr>
     <td valign="middle" id="ta">
     <label for="title">Title *</label>
     </td>
     <td valign="middle" id="ta">
     <select name="title">
     <option value="0">Title</option>
     <option value="1">Mr.</option>
     <option value="2">Ms.</option>
     <option value="3">Mrs.</option>
     </select></td></tr><tr><td id="ta">
      <label for="first_name">First Name *</label>
     </td>
     <td valign="middle" id="ta">
      <input  type="text" name="first_name" maxlength="50" size="30" required="required">
     </td>
    </tr>
    <tr>
     <td valign="middle" id="ta">
      <label for="last_name">Last Name *</label>
     </td>
     <td valign="middle" id="ta">
      <input  type="text" name="last_name" maxlength="50" size="30" required="required">
     </td>
    </tr>
    <tr>
     <td valign="middle" id="ta">
      <label for="email">Email Address *</label>
     </td>
     <td valign="middle" id="ta">
      <input  type="text" name="email" maxlength="80" size="30" required="required">
     </td>
    </tr>
    <tr>
     <td valign="middle" id="ta">
      <label for="telephone">Telephone Number *</label>
     </td>
     <td valign="middle" id="ta">
      <input  type="text" name="telephone" maxlength="30" size="30" required="required">
     </td>
    </tr>
    <tr>
     <td valign="middle" id="ta">
      <label for="comments">Details</label>
     </td>
     <td valign="middle" id="ta">
      <textarea  name="comments" maxlength="100000" cols="25" rows="6"></textarea>
     </td>
    </tr>
    <tr>
    <td valign="middle" id="ta">
     <label for="file">Or upload a file (only word, excel or pdf)</label>
    </td>
    <td valign="middle" id="ta">
    <input type="file" name="file">
    </td>
    </tr>
    <tr>
     <td colspan="2" style="text-align:center" id="ta">
      <input type="submit" value="Submit">
     </td>
    </tr>
    </table>
    </form>

For reference, you may go to http://rsadvisories.com
Edited by ayushkhemka
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.