jQuery Contact Form with Attachment using PHP

In 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 email.

View Demo

Contact Form with File Attachment

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

jquery-ajax-contact-form

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){
$("#frmContact").on('submit',(function(e){
	e.preventDefault();
	$('#loader-icon').show();
	var valid;	
	valid = validateContact();
	if(valid) {
		$.ajax({
		url: "contact_mail.php",
		type: "POST",
		data:  new FormData(this),
		contentType: false,
		cache: false,
		processData:false,
		success: function(data){
		$("#mail-status").html(data);
		$('#loader-icon').hide();
		},
		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,

require('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$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;
$mail->MsgHTML($_POST["content"]);

if(is_array($_FILES)) {
	$mail->AddAttachment($_FILES['attachmentFile']['tmp_name'],$_FILES['attachmentFile']['name']); 
}

$mail->IsHTML(true);
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