PHPMailer enviar email adjunto archivos [Ejemplo Completo]
Cómo enviar correos electrónicos con archivos adjuntos en PHP
PHPMailer enviar email adjunto. En este artículo desarrollaremos un tema relacionado con PHPMailer y de cómo podemos enviar un correo electrónico con archivos adjuntos sobre PHP, haciendo uso de la biblioteca PHPMailer.
Es una biblioteca de clases PHP que se utilizan para enviar correo electrónico y esta clase tiene más funcionalidad en comparación con la función simple PHP mail(), incluyendo archivo adjunto, plantillas HTML, etc.
¿Que hay dentro?
PHPMailer enviar email adjunto ¿Cómo hacerlo?
Lo primero es completar una serie de pasos que detallare a continuación
- Crear un formulario HTML
- Disponer de un email para envíos
- Declarar la librería PHPMailer
- Configurar un email vía SMTP
- Incorporar las variables de adjuntar archivo
- Enviar el email Adjunto
Si cumplimos esos pasos podremos enviar correos electrónicos con archivo adjunto mediante el uso de PHPMailer de envío de formulario PHP.

¿Cómo funciona el Script?
Voy a suponer que necesito enviar un informe con un documento adjunto en el trabajo y lo podemos hacer fácilmente con este método.
Básicamente necesitamos estos componentes y son los siguientes:
- Disponer de un formulario HTML5 y dentro de este formulario habilitar un campo de tipo email (Email destinatario) y un campo de tipo “file”
<input type="file" name="myfile">
. Sin embargo, este tipo de input nos permitirá seleccionar un archivo de nuestro ordenador. - Este formulario haciendo uso del método POST subirá el fichero a una carpeta en el servidor.
- La librería PHPMailer recibirá los datos del formulario para poder procesar el envío a ese email destinatario y el archivo que ha sido subido al servidor a través de la variable
$mail->AddAttachment($archivo);
- Por último, la variable
$mail->Send()
se encargará de enviar el email junto al archivo. - Después de enviar con éxito el correo electrónico, hemos creado una instrucción para eliminar el archivo cargado en nuestro servidor.
PHPMailer enviar email adjunto: Estructura
A) Declarar librerías
Son librerías necesarias para la interfaz gráfica por ejemplo el Bootstrap y jQuery
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-pQQkAEnwaBkjpqZ8RU1fF1AKtTcHJwFl3pblpTlHXybJjHpMYo79HY3hIi4NKxyj" crossorigin="anonymous"></script>
B) El formulario HTML5
El formulario tiene que tener el atributo enctype="multipart/form-data"
para poder enviar y subir al servidor, caso contrario no podrá subir archivos.
<div class="card-body"> <form action="enviar.php" method="post" enctype="multipart/form-data"> <div class="row"> <div class="col-md-5"> <div class="mb-3"> <label>Codigo cliente</label> <input type="text" name="codigo" placeholder="Ingrese código" class="form-control" required /> </div> <div class="mb-3"> <label>Nombre</label> <input type="text" name="nombre" placeholder="Ingrese nombre" class="form-control" required> </div> <div class="mb-3"> <label>Email</label> <input type="email" name="email" class="form-control" placeholder="Ingrese Email" required /> </div> </div> <div class="col-md-7"> <div class="row"> <div class="col-md-12"> <div class="mb-3 files color"> <label> Seleccione: Imagen, PDF </label> <input type="file" class="form-control" name="resume" accept="image/*, .pdf" required> </div> </div> </div> </div> </div> <hr> <div class="mb-3" align="center"> <button name="submit" value="" class="btn btn-primary">Enviar informe</button> </div> </form> </div>
C) Proceso de la información
Este código PHP procesara la información enviada desde el formulario cumpliendo un rol fundamental en el ejemplo. Además, le hemos agregado una función para limpiar los envíos del formulario.
<?php $message = ''; function clean_text($string) { $string = trim($string); $string = stripslashes($string); $string = htmlspecialchars($string); return $string; } $codigo = clean_text($_POST["codigo"]); $nombre = clean_text($_POST["nombre"]); $email = clean_text($_POST["email"]); if(isset($_POST["submit"])) { $path = 'upload/' . $_FILES["resume"]["name"]; move_uploaded_file($_FILES["resume"]["tmp_name"], $path); $message = ' <h3 align="center">Detalles del informe</h3> <table border="1" width="100%" cellpadding="5" cellspacing="5"> <tr> <td width="30%">Codigo</td> <td width="70%">'.$codigo.'</td> </tr> <tr> <td width="30%">Nombre</td> <td width="70%">'.$nombre.'</td> </tr> <tr> <td width="30%">Email</td> <td width="70%">'.$email.'</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'; $mail->Port = '80'; //Sets the default SMTP server port $mail->SMTPAuth = true; //Sets SMTP authentication. $mail->Username = 'xxxxxxx'; //Sets SMTP username $mail->Password = 'xxxxxxx'; //Sets SMTP password $mail->SMTPSecure = ''; //Sets connection prefix. Options are "", "ssl" or "tls" $mail->From = $email; //Sets the From email address for the message $mail->FromName = $nombre; //Sets the From name of the message $mail->AddAddress('mai@mimail.com', 'My Name'); //Adds a "To" address $mail->WordWrap = 50; $mail->IsHTML(true); //Sets message type to HTML $mail->AddAttachment($path); //Adds an attachment from a path on the filesystem $mail->Subject = 'Enviar informe'; //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">Informe enviado correctamente</div>'; unlink($path); } else { $message = '<div class="alert alert-danger">Hubo un error al procesar envio</div>'; } } ?>
FICHEROS COMPLETOS
A continuación, veremos los ficheros con el código completo.
1.- Fichero Index.php
Es la parte donde el usuario llena los datos en el formulario y provee de un fichero adjunto desde el ordenador.
<!DOCTYPE html> <html> <head> <title>PHPMailer enviar email adjunto archivos</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-pQQkAEnwaBkjpqZ8RU1fF1AKtTcHJwFl3pblpTlHXybJjHpMYo79HY3hIi4NKxyj" crossorigin="anonymous"></script><link rel="stylesheet" href="css/style.css"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12" style="margin:0 auto; float:none;"> <br /> <h4>PHPMailer enviar email adjunto archivos</h4> <hr> <div class="card"> <h5 class="card-header">Enviar informe</h5> <div class="card-body"> <form action="enviar.php" method="post" enctype="multipart/form-data"> <div class="row"> <div class="col-md-5"> <div class="mb-3"> <label>Codigo cliente</label> <input type="text" name="codigo" placeholder="Ingrese código" class="form-control" required /> </div> <div class="mb-3"> <label>Nombre</label> <input type="text" name="nombre" placeholder="Ingrese nombre" class="form-control" required> </div> <div class="mb-3"> <label>Email</label> <input type="email" name="email" class="form-control" placeholder="Ingrese Email" required /> </div> </div> <div class="col-md-7"> <div class="row"> <div class="col-md-12"> <div class="mb-3 files color"> <label> Seleccione: Imagen, PDF </label> <input type="file" class="form-control" name="resume" accept="image/*, .pdf" required> </div> </div> </div> </div> </div> <hr> <div class="mb-3" align="center"> <button name="submit" value="" class="btn btn-primary">Enviar informe</button> </div> </form> </div> </div> </div> </div> </div> </body> </html>
2.- Fichero enviar.php
Todo el código completo del fichero enviar.php que como ya dijimos se encargara de recibir los valores del formulario, subir el documento y enviar un email al destinatario.
<?php $message = ''; function clean_text($string) { $string = trim($string); $string = stripslashes($string); $string = htmlspecialchars($string); return $string; } $codigo = clean_text($_POST["codigo"]); $nombre = clean_text($_POST["nombre"]); $email = clean_text($_POST["email"]); if(isset($_POST["submit"])) { $path = 'upload/' . $_FILES["resume"]["name"]; move_uploaded_file($_FILES["resume"]["tmp_name"], $path); $message = ' <h3 align="center">Detalles del informe</h3> <table border="1" width="100%" cellpadding="5" cellspacing="5"> <tr> <td width="30%">Codigo</td> <td width="70%">'.$codigo.'</td> </tr> <tr> <td width="30%">Nombre</td> <td width="70%">'.$nombre.'</td> </tr> <tr> <td width="30%">Email</td> <td width="70%">'.$email.'</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'; $mail->Port = '80'; //Sets the default SMTP server port $mail->SMTPAuth = true; //Sets SMTP authentication. $mail->Username = 'xxxxxxx'; //Sets SMTP username $mail->Password = 'xxxxxxx'; //Sets SMTP password $mail->SMTPSecure = ''; //Sets connection prefix. Options are "", "ssl" or "tls" $mail->From = $email; //Sets the From email address for the message $mail->FromName = $nombre; //Sets the From name of the message $mail->AddAddress('mai@mimail.com', 'My Name'); //Adds a "To" address $mail->WordWrap = 50; $mail->IsHTML(true); //Sets message type to HTML $mail->AddAttachment($path); //Adds an attachment from a path on the filesystem $mail->Subject = 'Enviar informe'; //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">Informe enviado correctamente</div>'; unlink($path); } else { $message = '<div class="alert alert-danger">Hubo un error al procesar envio</div>'; } } ?>
3.- Archivo style.css
Si bien es esta usando el frameworkBootstrap para la interfaz grafica, se usara unas clases de estilos para gestionar el campo subida de archivos (drag and drop file input)
input[type="file"] { font-size:14px; } .files input { outline: 2px dashed #92b0b3; outline-offset: -10px; -webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear; transition: outline-offset .15s ease-in-out, background-color .15s linear; padding: 120px 0px 85px 35%; text-align: center !important; margin: 0; width: 100% !important; } .files input:focus{ outline: 2px dashed #92b0b3; outline-offset: -10px; -webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear; transition: outline-offset .15s ease-in-out, background-color .15s linear; border:1px solid #92b0b3; } .files{ position:relative} .files:after { pointer-events: none; position: absolute; top: 60px; left: 0; width: 50px; right: 0; height: 56px; content: ""; background-image: url(109612.png); display: block; margin: 0 auto; background-size: 100%; background-repeat: no-repeat; } .color input{ background-color:#f1f1f1;} .files:before { position: absolute; bottom: 10px; left: 0; pointer-events: none; width: 100%; right: 0; height: 37px; content: "o arrastra el archivo aquí. "; display: block; margin: 0 auto; color: #2ea591; font-weight: 600; text-transform: capitalize; text-align: center; }
Conclusión
Hemos aprendido a enviar correo electrónico con archivo adjuntos y que son enviados mediante el uso de la biblioteca PHPMailer en PHP.
Además, hemos usado SMTP para enviar email y es muy recomendable utilizarlo para que nuestros emails no lleguen a parar en la carpeta spam.
Recordemos, que enviar email también se puede hacer con la función mail() de PHP, pero no es una función tan segura y carece de algunas funcionalidades como, por ejemplo: enviar contenido HTML o imágenes que con PHPMailer podemos lograr con simples líneas de código.
Hola Nestor, saludes desde Colombia.
He completado todos los datos del código enviar.php. Lo he subiso al servidor pero al procesar, sube el adjunto a la carpeta temporal, pero al enviar el email siempre saca error lo he echo en dos servidores distinto y ambos saca error
“hubo error al procesar el envió” no especifica el error y en el archivo erro.log no aparece nada
dejo el código
<?php
$message = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
$codigo = clean_text($_POST["codigo"]);
$nombre = clean_text($_POST["nombre"]);
$email = clean_text($_POST["email"]);
if(isset($_POST["submit"]))
{
$path = 'upload/' . $_FILES["resume"]["name"];
move_uploaded_file($_FILES["resume"]["tmp_name"], $path);
$message = '
Detalles del informe
Codigo
‘.$codigo.’
Nombre
‘.$nombre.’
Email
‘.$email.’
‘;
require ‘class/class.phpmailer.php’;
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = ‘smtp.gmail.com’;
$mail->Port = ‘587’; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication.
$mail->Username = ‘alguien@gmail.com’; //Sets SMTP username
$mail->Password = ‘*******’; //Sets SMTP password
$mail->SMTPSecure = ”; //Sets connection prefix. Options are “”, “ssl” or “tls”
$mail->From = $email; //Sets the From email address for the message
$mail->FromName = $nombre; //Sets the From name of the message
$mail->AddAddress(‘williamjosepardo@gmail.com’); //Adds a “To” address
$mail->WordWrap = 50;
$mail->IsHTML(true); //Sets message type to HTML
$mail->AddAttachment($path); //Adds an attachment from a path on the filesystem
$mail->Subject = ‘Enviar informe’; //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 = ‘Informe enviado correctamente’;
unlink($path);
}
else
{
$message = ‘Hubo un error al procesar envio’;
}
}
?>
PHPMailer enviar email adjunto archivos
PHPMailer enviar email adjunto archivos
Respuesta del sistema