Please support us by disabling ad blocker for smarttutorials.net ...

Send Email with File Attachment (PDF, word files and images etc..) in PHP

Posted by & filed under CSS, HTML5, PHP.

Please go through the Following link to refer same tutorial

 

PHP Script to Send Email with Attachment

 

this page has some issues with crayon syntax highlighter

 

I had searched in Google for long time for the script to send an email with file attachment (all types of file pdf files,word files and images etc……). It was hard thing to find out exact script. Here I had source code as well steps to implement email form attachment.

More importantly the mail will reaches inbox, mainly avoids as spam message.

This article shows you how to create a PHP based email form that supports file attachment.

The whole process consists of two steps

1. create an html form with attachment.
2. Then create php file that process data from the html form.

php script to send mail with attachment

Demo

The HTML form with file upload box :

The code for an HTML form with a file upload box is given below. User can click on the ‘Browse’ button to select the file from his/her local machine.


<div>
<h1>Mail Demo Page</h1>
</div>
<div>
<form action='mail.php' method='post' id='mailForm' enctype='multipart/form-data'>
<table>
<tr>
<td> Name : </td>
<td><input type="text" id="name" name="name" placeholder='User Name'/>
<div id="invalid-name"></div>
</td>
</tr>
<tr>
<td> E-mail : </td>
<td><input type="email" id="email" name="email" placeholder='E-Mail'/>
<div id="invalid-email"></div>
</td>
</tr>
<tr>
<td> From E-mail : </td>
<td><input type="email" id="femail" name="femail" placeholder='From E-Mail'/>
<div id="invalid-femail"></div>
</td>
</tr>

<tr>
<td> Phone : </td>
<td><input type="tel" id="phone" name="phone" placeholder='Phone'/>
<div id="invalid-phone"></div>
</td>
</tr>
<tr>
<td> Image : </td>
<td><input type="file" id="image" name="image" placeholder='Image' accept="image/*"> <div id="invalid-image"></div></td>

</tr>

<tr>
<td> Message : </td>
<td><textarea cols="27" rows="5" id="message" name="message" placeholder='Message' value=''></textarea><div id="invalid-message"></td>

</tr>

<tr>
<td colspan="2"> <input type="submit" value="Send Mail!" id='submit_btn' name="submit_btn"/></td>
</tr>
<table>
</form>
</div>

The form will look like this:

php script to send mail with attachment

HTML form for Sending Email with File Attachment in PHP.

Please note that we have added:

“enctype=”multipart/form-data”
while defining the <form> tag. This is to tell the browser that this form will be used to upload files. Then we have added the “name” and “email” fields to collect the user info. The third form field is the file upload box.
<input type=”file” name=”image”>
On hitting the “Submit” button, the form data along with the file data is posted to the script pointed to by the ‘action’ attribute of the form.
php script to send mail with attachment

Download

Now we almost finished form designing part.

Now just follow php part coding. I am using php mail plugin to send an email with attachment.

Step 1:

Create mail.php file and add the following php file (class.phpmailer.php).

require 'class.phpmailer.php';

Step 2:

Now add to email ID.


$to = "Your email ID";
$mail->AddAddress($to);

Step 3:

Now get from email id and name of the user.


$mail->From = $_POST['femail'];
$mail->FromName = $_POST['name'];

Step 4:

Now add subject of the mail.

$mail->Subject = "Test Email using PHP";

Step 5:

Now get message from the html form.


$body = "<table>
<tr>
<th colspan='2'>This Sample Mail</th>
</tr>

<tr>
<td>Name :</td>
<td>".$_POST['name']."</td>
</tr>

<tr>
<td>E-mail : </td>
<td>".$_POST['email']."</td>
</tr>

<tr>
<td>Phone : </td>
<td>".$_POST['phone']."</td>
</tr>
<tr> <td>Message : </td> <td>".$_POST['message']."</td> </tr> <table>";
$body = preg_replace('/\\\\/','', $body); //Strip backslashes $mail->MsgHTML($body);

Step 6:

Finally get the attachment and send it.

    $mail->AddAttachment($_FILES['image']['tmp_name'],
    $_FILES['image']['name']);

    $mail->IsHTML(true); // send as HTML

    $mail->Send();
    echo 'Message has been sent.';
Here is the full php source code.

<?php
/**
* Simple example script using PHPMailer with exceptions enabled
* @package phpmailer
* @version $Id$
*/

require 'class.phpmailer.php';

try {
$mail = new PHPMailer(true); //New instance, with exceptions enabled

$to = $_POST['email'];
$mail->AddAddress($to);
$mail->From = $_POST['femail'];
$mail->FromName = $_POST['name'];
$mail->Subject = "Test Email using PHP";

$body = "<table>
<tr>
<th colspan='2'>This Sample Mail</th>
</tr>

<tr>
<td style='font-weight:bold'>Name :</td>
<td>".$_POST['name']."</td>
</tr>

<tr>
<td style='font-weight:bold'>E-mail : </td>
<td>".$_POST['email']."</td>
</tr>

<tr>
<td style='font-weight:bold'>Phone : </td>
<td>".$_POST['phone']."</td>
</tr>

<tr>
<td style='font-weight:bold'>Message : </td>
<td>".$_POST['message']."</td>
</tr>
<table>";
$body = preg_replace('/\\\\/','', $body); //Strip backslashes
$mail->MsgHTML($body);

$mail->IsSMTP(); // tell the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP server port
//$mail->Host = "mail.yourdomain.com"; // SMTP server
//$mail->Username = "name@domain.com"; // SMTP server username
//$mail->Password = "password"; // SMTP server password

$mail->IsSendmail(); // tell the class to use Sendmail
$mail->AddReplyTo("admin@smarttutorials.net");
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->WordWrap = 80; // set word wrap

$mail->AddAttachment($_FILES['image']['tmp_name'],
$_FILES['image']['name']);
$mail->IsHTML(true); // send as HTML
$mail->Send();
echo 'Message has been sent.';
} catch (phpmailerException $e) {
echo $e->errorMessage();
}
?>
 

Hope this code works well for all for sending all type of files (word files,PDF files and images etc………..)

 

php script to send mail with attachment

Example Php Email with File attachment and Images

Please refer this cool tutorial on Send an E-Mail with Attachment Using jQuery, Ajax and PHP without Refrshing a Page

 

 

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni[at]smarttutorials.net

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

  • the attach a file is working properly but body content name email and message not working..
    can’t display these details

  • muni

    Pls cheack clearly……. it’s working fine……..

  • that my mistake .. it work properly thanks alot friend….

    again thanks……

  • $headers = “From: admin@server.com\r\n”;

    i am change this mail not received .. how to fix this prob…

  • $headers = “From: admin@server.com\r\n”;

    insted of this i am using Post email id as from address how can i set that email id insted of this ($headers = “From: admin@server.com\r\n”;)… please help me….
    i am change that header id in to other id (except our server email id) its not working give me one solution plzzzzzzzzzzzzzz…….

  • muni

    Hi Santhosh,

    I had checked. I’m getting post email like that.
    $to = $_POST[’email’];

    and assigning this in header as from email

    $headers = “From: $to\r\n”;

    it’s working fine.

    as well see demo at
    http://smarttutorials.net/demo/mail1.php

  • dear muni,

    r u change header or any modification exept this
    ($to = $_POST[’email’];
    and assigning this in header as from email
    $headers = “From: $to\r\n”;)

    i did same way but my server did not sent any mail.. then i was chnage the headers to.
    $headers = “From: admin@server.com\r\n”;

    the mail sent working … what is the prob… how to solve this miracle….

  • my code bellow

    $from = $_POST[’email’];
    $to = “test@gmail.com”;
    $bodymsg=”Name : “.$_POST[‘name’].””;
    $bodymsg.=”Email : “.$_POST[’email’].””;
    $bodymsg.=”Contact No : “.$_POST[‘number’].””;
    $subject = ‘Resume’;
    $bound_text = “test”;
    $bound = “–“.$bound_text.”\r\n”;
    $bound_last = “–“.$bound_text.”–\r\n”;

    //$headers = “From: admin@server.com\r\n”;
    $headers = “From: $from\r\n”;
    $headers .= “MIME-Version: 1.0\r\n”

  • dear muni,

    thanks it working fine… thanks alot for spend ur valuable time and ur php codes….

  • Veronika

    Hi muni,
    thanks a lot for your code!

    I’m new to php and have a trouble editing your code. Is there a way to send multiple entries form input fields in the body of the email?

    For example in your code we are just sending a “message” as a body of the email. What if you need to send “message”, “phone”, “email”?

    Thanks in advance for your help!

  • muni

    Hi Veronika,

    Yes you can send multiple form entries in the body of mail, just get multiple form entries and concatenate those fields like in the below code

    $bodymsg=$_POST[‘message’]. ”
    phone Number :” . $_POST[‘phone’] . “
    Email”.$_POST[’email’] ;

    I had updated in demo page and in source code too.. Download source if you needed……

  • Gopi

    Hi muni,
    I am Gopi,I run your code in xampp server i got some error,
    please suggest me how to rectify that error.

    error is :

    Could not execute: /var/qmail/bin/sendmail

  • muni

    Hi Gopi,

    pls follow this tutorial, and download source code and run.

    http://www.smarttutorials.net/php-script-to-send-email-with-attachment/

    If face any issues let me know…

    Regards,

    muni

  • I want to send Doc and PDF file so what changes i have to do in code can you help me please

  • Devendra

    Hi muni,
    i run it on server it get below error
    please suggest me how to rectify that error.

    error is :

    Could not execute: /usr/sbin/sendmail

  • Nitin Jadhav

    Nice Tut muni.
    working fine.
    Thanx

  • Rinku jat

    same problem is here
    how can i solve this

  • Rinku jat

    Hi muni,
    i run it on server it get below error
    please suggest me how to rectify that error.

    error is :

    Could not execute: /usr/sbin/sendmail

  • Andrea Sanchez

    This was so simple, great explanation, just what I was looking for! thanks a lot!

  • NARESHBABU

    Hi muni,
    i run it on server it get below error
    please suggest me how to rectify that error.

    error is :

    Could not execute: /usr/sbin/sendmail

  • karpagavalli

    hi sir dowload link

Get Instant Script Download Access!