En este tutorial vamos a ver cómo enviar un email con adjuntos utilizando jQuery, Ajax y PHP sin refrescar la página, es decir, de la manera más inmediata.
Paso 1
Crea un fichero index.php y añade el siguiente código HTML para diseñar el formulario que se enviará por email.
<div class="title">
<h1>Mail Demo Page</h1>
</div>
<div class="mail">
<div id='message1'>
<img id='close' src='images/close.png'/>
<h2>Mail Sent Successfully!</h2>
<p>We will be in touch soon.</p>
<img id='checkmark' src='images/check.png'/>
</div>
<form action='mail.php' method="post" id='mailForm' enctype='multipart/form-data'>
<table>
<tr>
<td class="label"> Name : </td>
<td><input type="text" id="name" name="name" class="form-input" placeholder='User Name'/></td>
<td class="status"></td>
</tr>
<tr>
<td class="label"> E-mail : </td>
<td><input type="email" id="email" name="email" class="form-input" placeholder='E-Mail'/></td>
<td class="status"></td>
</tr>
<tr>
<td class="label"> From E-mail : </td>
<td><input type="email" id="femail" name="femail" class="form-input" placeholder='From E-Mail'/></td>
<td class="status"></td>
</tr>
<tr>
<td class="label"> Phone : </td>
<td><input type="tel" id="phone" name="phone" class="form-input" placeholder='Phone'/></td>
<td class="status"></td>
</tr>
<tr>
<td class="label"> Image : </td>
<td><input type="file" id="image" name="image" class="form-input" placeholder='Image' accept="image/*"></td>
<td class="status"></td>
</tr>
<tr>
<td class="label"> Message : </td>
<td><textarea cols="27" rows="5" id="message" name="message" placeholder='Message'></textarea></td>
<td class="status"></td>
</tr>
<tr>
<td colspan="2"> <input type="submit" value="Send Mail!" id='submit_btn' name="submit_btn" class="submit_btn"/></td>
</tr>
</table>
</form>
</div>
Paso 2
Crea el fichero style.css y añade el siguiente código css para darle estilo a nuestro formulario
* { background-color: #16a085; margin: 0; padding: 0; } @font-face{ font-family: Lobster; src: url('Lobster.otf'); } table{ color: #fff; font-size: 20px; } .error_msg{ color: red; } td{ padding: 20px 0 0 0; } textarea{ border-radius: 5px; color: #fff; font-size : 17px; font-family: Verdana; } textarea:focus{ color: #FF9900; border: 2px solid green; } .mail{ width: 500px; margin:0 auto; } .label{ text-align: right; padding-right: 20px; } #image{ height: 30px; } .title{ font-family: Lobster; text-align: center; font-size: 35px; color: #FFf; margin: 50px 0 10px 0; text-decoration:underline; } .form-input{ width: 275px; height: 40px; border-radius: 5px; color: #999; font-size : 17px; background: #fff; border: 2px solid #fff; } .form-input:focus{ color: #3D991F; border: 2px solid green; } .submit_btn:hover{ background: green; border: 2px solid green; color: #fff; } .submit_btn{ margin-left: 140px; width: 280px; height: 45px; border-radius: 5px; color: #fff; background-color: #EE872A; font: bold 15px Verdana; margin-bottom: 100px; border: 2px solid #EE872A; } #message{ background: #fff; color: #999; border: 2px solid #fff; } em.error { background:url("unchecked.gif") no-repeat 0px 0px; padding-left: 16px; color: #ff0000; font-weight: bold; } em.success { background:url("checked.gif") no-repeat 0px 0px; padding-left: 16px; color: #33ff55 !important; } form.cmxform label.error { margin-left: auto; width: 250px; color: red; } #warning { display: none; } .status{ width : 250px; position: absolute; } #message1{ display:none; margin-left: 50px; margin-top: 100px; color: #fff; width: 400px; height: 100px; border: 2px solid #fff; border-radius: 10px; position: relative; } #message1 h2, #message1 p{ text-align: center; } #message1 #checkmark{ margin-left: 170px; } #close{ position: absolute; right: -8px; top: -10px; } .hide{ display: none; } .preview{ width: 400px; margin: 20px 0 50px 430px; border: 10px dotted orange; }
Con esto, habremos completado la parte del diseño de nuestro formulario.
Paso 3
Añade las librerías de jQuery en tu archivo index.php
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
Paso 4
Utilizamos el método .ajaxForm() para enviar los datos del formulario al archivo mail.php. Aquí tienes la sintáxis.
$('form').ajaxForm({ beforeSubmit: function() { // validation script goes here }, success: function(msg) { // Success message goes here }, complete: function(xhr) { // some logic script goes here } });
El siguiente script comprueba si el formulario es válido o no, en la función callback beforesubmit.
var flag= $('#mailForm').valid(); if(!flag){ return false; }
Si el formulario no es válido, entonces no permitimos que se envíe. El siguiente script oculta el formulario y muestra el mensaje de ok una vez que se haya hecho submit del formulario y todo haya ido sobre ruedas.
$("#mailForm").addClass("hide"); $("#message1").show();
El siguiente evento click oculta el mensaje de ok y muestra el formulario limpio para que el usuario pueda hacer uso otra vez de él.
$('#close').click(function(){ $('#message1').hide(); $("#mailForm").removeClass("hide"); $('input[type=text],input[type=email],textarea,input[type=tel],input[type=file]').val(''); location.reload(); });
Aquí tienes el script completo de jQuery.
<script>
(function() {
$('form').ajaxForm({
beforeSubmit: function() {
//return $('#mailForm').validate().form();
$("#mailForm").validate({
rules: {
name: {
required: true,
minlength : 3
},
email:{
required: true,
email: true
},
phone: {
required : true,
number:true,
minlength : 10,
maxlength : 11
},
image: "required",
message: "required",
femail:{
required: true,
email: true
}
},
messages: {
name: {
required:"Please enter your name",
minlength: "Please enter a valid name"
},
email:{
required: "Please enter your email",
minlength: "Please enter a valid email address",
},
phone: {
required: "Please enter your phone number",
minlength: "Please enter your valid phone number",
maxlength: "Please enter your valid phone number"
},
image: "Please Choose your image",
message: "Please enter your message",
femail: {
required: "Please enter your email",
minlength: "Please enter a valid email address",
}
},
debug: true,
errorElement: "em",
errorContainer: $("#warning, #summary"),
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
},
success: function(label) {
label.text("ok!").addClass("success");
}
});
var flag= $('#mailForm').valid();
if(!flag){
return false;
}
},
success: function(msg) {
alert(msg);
//$("#mailForm").addClass("hide");
//$("#message1").show();
},
complete: function(xhr) {
$("#mailForm").addClass("hide");
$("#message1").show();
$('#status').html(xhr.responseText);
}
});
$('#close').click(function(){
$('#message1').hide();
$("#mailForm").removeClass("hide");
$('input[type=text],input[type=email],textarea,input[type=tel],input[type=file]').val('');
location.reload();
});
})();
</script>
Paso 5
Ahora vamos con la parte PHP. Utilizo la librería phpmailer para facilitarme el hecho de enviar un email con adjuntos. Crea el fichero mail.php y añade la librería phpmailer.
require 'class.phpmailer.php';
Paso 6
Ahora añadimos a qué dirección de correo quieres enviar el email.
$to = "Your email ID"; $mail->AddAddress($to);
Paso 7
Obtenemos el email y el nombre del usuario que nos quiere enviar un email.
$mail->From = $_POST['femail']; $mail->FromName = $_POST['name'];
Paso 8
Ahora añadimos el asunto del correo.
$mail->Subject = "Test Email using PHP";
Paso 9
Obtenemos el mensaje del formulario html
$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);
Paso 10
Finalmente obtenemos el adjunto y lo enviamos.
$mail->AddAttachment($_FILES['image']['tmp_name'], $_FILES['image']['name']); $mail->IsHTML(true); // send as HTML $mail->Send(); echo 'Message has been sent.';
Aquí tienes el código fuente PHP completo.
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 = "[email protected]"; // SMTP server username
//$mail->Password = "password"; // SMTP server password
$mail->IsSendmail(); // tell the class to use Sendmail
$mail->AddReplyTo("[email protected]");
$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();
}
Fuente: smarttutorials.net