Saturday, 28 October 2017

How to send email with attachment in PHP



In this Post we have discuss one more topic related to PHPMailer Class and here we have discuss how can we send an Email with File attachment in PHP by using PHPMailer Library. We have received so many request from our viewer for publish web tutorial on sending of Email with Attachment by using PHPMailer from PHP form submission. We have already publish web tutorial on how to send email on PHP form submission and how can we send bulk email by using PHP with Ajax without refresh of web page. But in this post we have discuss something advance like how to send email with attach uploaded file by using PHPMailer Library in PHP.

PHPMailer is a PHP Class library which are used for sending email and this class has more functionality compared to the simple PHP mail() function including file attachment also. It is very useful if you have SMTP details then you can use that details into your PHP script and from your application you can send an email and you can also attach file with email on form submission by using this PHPMailer class.

For discuss how can we attach file sending of email by using PHPMailer in PHP. So here we have make simple programmer registration form in which programmer can fill their details. In that registration form we have add one file tag for programmer to attach resume. In this form all fields are compulsory and for form validation we have use HTML 5 validation. By using this validation we do not want to required to write any additional code for form validation. For attach file in an Email, so want to first upload file on our server folder and from that uploaded file path we can attach within mail by using AddAttachment() method of PHPMailer class. After attachment of file we can send email with file attachment using PHPMailer library. After successfully sending of email we have remove uploaded file from our space. So this way for attach file with email sending we want to temporary store on our space and after remove from our space. This is our simple tutorial on How to send email with attachment in PHP by using PHPMailer.




Source Code


index.php



<?php
//index.php

$message = '';

function clean_text($string)
{
 $string = trim($string);
 $string = stripslashes($string);
 $string = htmlspecialchars($string);
 return $string;
}

if(isset($_POST["submit"]))
{
 $programming_languages = '';
 foreach($_POST["programming_languages"] as $row)
 {
  $programming_languages .= $row . ', ';
 }
 $programming_languages = substr($programming_languages, 0, -2);
 $path = 'upload/' . $_FILES["resume"]["name"];
 move_uploaded_file($_FILES["resume"]["tmp_name"], $path);
 $message = '
  <h3 align="center">Programmer Details</h3>
  <table border="1" width="100%" cellpadding="5" cellspacing="5">
   <tr>
    <td width="30%">Name</td>
    <td width="70%">'.$_POST["name"].'</td>
   </tr>
   <tr>
    <td width="30%">Address</td>
    <td width="70%">'.$_POST["address"].'</td>
   </tr>
   <tr>
    <td width="30%">Email Address</td>
    <td width="70%">'.$_POST["email"].'</td>
   </tr>
   <tr>
    <td width="30%">Progamming Language Knowledge</td>
    <td width="70%">'.$programming_languages.'</td>
   </tr>
   <tr>
    <td width="30%">Experience Year</td>
    <td width="70%">'.$_POST["experience"].'</td>
   </tr>
   <tr>
    <td width="30%">Phone Number</td>
    <td width="70%">'.$_POST["mobile"].'</td>
   </tr>
   <tr>
    <td width="30%">Additional Information</td>
    <td width="70%">'.$_POST["additional_information"].'</td>
   </tr>
  </table>
 ';
 
 require 'class/class.phpmailer.php';
 $mail = new PHPMailer;
 $mail->IsSMTP();        //Sets Mailer to send message using SMTP
 $mail->Host = 'smtpout.secureserver.net';  //Sets the SMTP hosts of your Email hosting, this for Godaddy
 $mail->Port = '80';        //Sets the default SMTP server port
 $mail->SMTPAuth = true;       //Sets SMTP authentication. Utilizes the Username and Password variables
 $mail->Username = 'xxxxxxx';     //Sets SMTP username
 $mail->Password = 'xxxxxxx';     //Sets SMTP password
 $mail->SMTPSecure = '';       //Sets connection prefix. Options are "", "ssl" or "tls"
 $mail->From = $_POST["email"];     //Sets the From email address for the message
 $mail->FromName = $_POST["name"];    //Sets the From name of the message
 $mail->AddAddress('web-tutorial@programmer.net', 'Webslesson');  //Adds a "To" address
 $mail->WordWrap = 50;       //Sets word wrapping on the body of the message to a given number of characters
 $mail->IsHTML(true);       //Sets message type to HTML
 $mail->AddAttachment($path);     //Adds an attachment from a path on the filesystem
 $mail->Subject = 'Application for Programmer Registration';    //Sets the Subject of the message
 $mail->Body = $message;       //An HTML or plain text message body
 if($mail->Send())        //Send an Email. Return true on success or false on error
 {
  $message = '<div class="alert alert-success">Application Successfully Submitted</div>';
  unlink($path);
 }
 else
 {
  $message = '<div class="alert alert-danger">There is an Error</div>';
 }
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>Send Email with Attachment in PHP using PHPMailer</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <div class="row">
    <div class="col-md-8" style="margin:0 auto; float:none;">
     <h3 align="center">Send Email with Attachment in PHP using PHPMailer</h3>
     <br />
     <h4 align="center">Programmer Register Here</h4><br />
     <?php print_r($message); ?>
     <form method="post" enctype="multipart/form-data">
      <div class="row">
       <div class="col-md-6">
        <div class="form-group">
         <label>Enter Name</label>
         <input type="text" name="name" placeholder="Enter Name" class="form-control" required />
        </div>
        <div class="form-group">
         <label>Enter Address</label>
         <textarea name="address" placeholder="Enter Address" class="form-control" required></textarea>
        </div>
        <div class="form-group">
         <label>Enter Email Address</label>
         <input type="email" name="email" class="form-control" placeholder="Enter Email Address" required />
        </div>
        <div class="form-group">
         <label>Select Programming Language</label>
         <select name="programming_languages[]" class="form-control" multiple required style="height:150px;">
          <option value=".NET">.NET</option><option value="Android">Android</option><option value="ASP">ASP</option><option value="Blackberry">Blackberry</option><option value="C">C</option><option value="C++">C++</option><option value="COCOA">COCOA</option><option value="CSS">CSS</option><option value="DHTML">DHTML</option><option value="Drupal">Drupal</option><option value="Flash">Flash</option><option value="HTML">HTML</option><option value="HTML 5">HTML 5</option><option value="IPAD">IPAD</option><option value="IPHONE">IPHONE</option><option value="Java">Java</option><option value="Java Script">Java Script</option><option value="Joomla">Joomla</option><option value="LAMP">LAMP</option><option value="Linux">Linux</option><option value="MAC OS">MAC OS</option><option value="Magento">Magento</option><option value="MySQL">MySQL</option><option value="Oracle">Oracle</option><option value="PayPal">PayPal</option><option value="Perl">Perl</option><option value="PHP">PHP</option><option value="Ruby on Rails">Ruby on Rails</option><option value="Salesforce.com">Salesforce.com</option><option value="SEO">SEO</option>
         </select>
        </div>
        
       </div>
       <div class="col-md-6">
        <div class="form-group">
         <label>Select Year of Experience</label>
         <select name="experience" class="form-control" required>
          <option value="">Select Experience</option>
          <option value="0-1 years">0-1 years</option>
          <option value="2-3 years">2-3 years</option>
          <option value="4-5 years">4-5 years</option>
          <option value="6-7 years">6-7 years</option>
          <option value="8-9 years">8-9 years</option>
          <option value="10 or more years">10 or more years</option>
         </select>
        </div>
        <div class="form-group">
         <label>Enter Mobile Number</label>
         <input type="text" name="mobile" placeholder="Enter Mobile Number" class="form-control" pattern="\d*" required />
        </div>
        <div class="form-group">
         <label>Select Your Resume</label>
         <input type="file" name="resume" accept=".doc,.docx, .pdf" required />
        </div>
        <div class="form-group">
         <label>Enter Additional Information</label>
         <textarea name="additional_information" placeholder="Enter Additional Information" class="form-control" required rows="8"></textarea>
        </div>
       </div>
      </div>
      <div class="form-group" align="center">
       <input type="submit" name="submit" value="Submit" class="btn btn-info" />
      </div>
     </form>
    </div>
   </div>
  </div>
 </body>
</html>





18 comments:

  1. Hi admin,
    First, thank for the post. I would like to ask a question

    What should I input in "xxxxxxx". I want users will input their email in the "Enter Email Address" but when I run the code, I had to put the same email in "$mail->Username" at that form to ensure the code will run correctly, if not it will not run.
    $mail->Username = 'xxxxxxx'; //Sets SMTP username
    $mail->Password = 'xxxxxxx'; //Sets SMTP password

    ReplyDelete
  2. i like this tutorial. Can you kindly try and do this with mysql? Thank you in advance.

    ReplyDelete
  3. Attachment not working

    ReplyDelete
  4. Thank you. I downloaded the source code. Please tell me what I have to change?
    Please mention the lines to edit.

    ReplyDelete
  5. When i click on submit i just get "there is an error".

    ReplyDelete
  6. Have you considered adding some form input validations. It will make this very advanced. Otherwise great work.

    ReplyDelete
  7. hi i am getting there is an error msg. how do i fix it.

    ReplyDelete
  8. I am getting error using local server xampp

    "There is an Error"

    ReplyDelete
  9. Hi getting a message saying there is a error please help

    ReplyDelete
  10. Hello.
    I am trying to create a system where my logged in clients can send emails to other clients whose email address they have added. Can this work out in php?

    ReplyDelete
  11. showing error msg......help me

    ReplyDelete
  12. I received a lot of error precisely in line 59

    ReplyDelete
  13. Hi. Nice work.
    Can you release resize image for attachment?
    Thank you.

    ReplyDelete
  14. By clicking submit button i am getting one error
    Error 404
    localhost
    Apache/2.4.39 (Win64) OpenSSL/1.0.2r PHP/7.1.29

    ReplyDelete
  15. require 'class/class.phpmailer.php how do i download

    ReplyDelete
  16. there is an error but not specify an error

    ReplyDelete