Ejemplo que consiste en enviar un email en localhost con XAMPP, mediante la función mail() que trae PHP, muy útil a veces para cuando trabajamos con nuestro proyecto php en local, y queremos ver el correo electrónico que nos ha enviado el archivo php en cuestión.
ÍNDICE
Descripción del ejemplo
Para realizar este ejemplo necesitaremos configurar XAMPP correctamente y también necesitaremos un programa que actue de servidor de correo, llamado: Test Mail Server Tool.
Una vez configurado XAMPP, lo que conseguimos es que los correos salientes en localhost, se envién desde localhost, y que no usemos el servidor que trae XAMPP para recibir correos: mailtodisk ya que a mí me parece mucho mejor Test Mail Server.
Configurar XAMPP
Lo único que tenemos que hacer para configurar XAMPP sería:
- Abrimos PHP.INI
- En la sección [mail function], le quitamos el ; a la línea:
;SMTP = localhost
y añadimos un ; para comentar la línea:
sendmail_path = "C:\xampp\mailtodisk\mailtodisk.exe"
…con lo que nos tiene que quedar el siguiente código:
[mail function] ;XAMPP: Comment out this if you want to work with an SMTP Server like Mercury SMTP = localhost smtp_port = 25 ; For Win32 only. ; http://php.net/sendmail-from sendmail_from = postmaster@localhost ; XAMPP IMPORTANT NOTE (1): If XAMPP is installed in a base directory with spaces (e.g. c:\program filesD:\xampp) fakemail and mailtodisk do not work correctly. ; XAMPP IMPORTANT NOTE (2): In this case please copy the sendmail or mailtodisk folder in your root folder (e.g. C:\sendmail) and use this for sendmail_path. ; XAMPP: Comment out this if you want to work with fakemail for forwarding to your mailbox (sendmail.exe in the sendmail folder) ;sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t" ; XAMPP: Comment out this if you want to work with mailToDisk, It writes all mails in the C:\xampp\mailoutput folder ; sendmail_path = "C:\xampp\mailtodisk\mailtodisk.exe"
Código PHP para enviar el email
El código para la función Mail() de php, sería el siguiente:
<?php
// El mensaje
$mensaje = "Esto es una prueba 1\r\nA ver si te llega correctamente 2\r\nUn saludo 3\r\n\n\n\nwww.ejemplocodigo.com";
// Si cualquier línea es más larga de 70 caracteres, se debería usar wordwrap()
$mensaje = wordwrap($mensaje, 70, "\r\n");
// Enviamos el email
mail('tu@direcciondeemail.com', 'Probando la funcion MAIL desde PHP', $mensaje);
echo "EMAIL ENVIADO...";
?>
Previsualización del ejemplo
Teniendo el Test Mail Server conectado, y supongamos que el archivo php de la función mail() se llamase “mail.php”, al poner en la barra del navegador http://localhost/mail.php nos debería de salir este email, si tenemos el Thunderbird:
Si no tenemos Thunderbird instalado para que nos lo abra de forma predeterminada, pues en la carpeta que hayamos configurado en el Test Mail Server para recibir los emails, tendremos dicho email en formato .eml que podremos abrir con cualquier editor de texto.