jQuery Contact Form with Attachment using PHP

In the previous tutorial, we have seen how to send contact form email using PHP and jQuery. In this tutorial, we are going see the code for sending file attachments with the contact form email. We are using PHPMailer through SMTP for sending an email.

View Demo

Contact Form with File Attachment

In this contact form, we have an additional input field to choose a file to be attached. Other than that, everything will be same. So, the form will be,


jQuery AJAX Function Triggers Mail Sending Script

On submitting above form, the jQuery script sends AJAX call with contact form data objects instead of query-string. The script is,

$(document).ready(function (e){
	var valid;	
	valid = validateContact();
	if(valid) {
		url: "contact_mail.php",
		type: "POST",
		data:  new FormData(this),
		contentType: false,
		cache: false,
		success: function(data){
		error: function(){} 	        

The form validation script is same as we have seen in previous contact form tutorial.

PHP Code Sending Contact Mail Attachment

In PHP file, we are using PHP Mailer via SMTP for sending attachment email. So, we have to download and include PHPMailer class and SMTP class for executing email script. This code will attach file attachment with the contact form email by using AddAttachment() function. The code is,

$mail = new PHPMailer();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port     = 587;  
$mail->Username = "Your SMTP UserName";
$mail->Password = "Your SMTP Password";
$mail->Host     = "Your SMTP Host";
$mail->Mailer   = "smtp";
$mail->SetFrom($_POST["userEmail"], $_POST["userName"]);
$mail->AddReplyTo($_POST["userEmail"], $_POST["userName"]);
$mail->AddAddress("recipient address");	
$mail->Subject = $_POST["subject"];
$mail->WordWrap   = 80;

if(is_array($_FILES)) {

if(!$mail->Send()) {
	echo "Problem in Sending Mail.";
} else {
	echo "Contact Mail Sent.";

View DemoDownload

This jQuery code tutorial was published on October 16, 2014.

↑ Back to Top