First, you must install a mail server, so that the function mail
works in localhost
or your server with support PHP
, now if you want to avoid installing a mail server, you could opt for the famous library PHPMailer
.
The function mail
of PHP
returns true
if it has been accepted, otherwise false
.
Note: It is important to keep in mind that although the email is accepted for sending, NO means that the email has reached the indicated destination.
Parameters to pass:
to
, Recipient / s of the mail.
subject
, Title of the email to send.
message
, Message to send. Each line should be separated with a CRLF ( \r\n
). The lines should not occupy more than 70 characters.
Optional
additional_headers
, String to insert at the end of the mail header. It is normally used to add extra headers ( From
, Cc
and Bcc
). Additional multiple headers should be separated with CRLF
( \r\n
).
additional_parameters
, The additional_parameters
parameter can be used to indicate additional options such as command line options to the program that is configured to be used when sending mail, defined by the sendmail_path
configuration option.
Practical example:
Send an email with extra headers.
<?php
$para = '[email protected]';
$titulo = 'El título';
$mensaje = 'Hola mundo :)';
$cabeceras = 'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
//Enviamos y comprobamos si ha sido aceptado.
if (mail($para, $titulo, $mensaje, $cabeceras)) {
echo 'El correo fue aceptado';
} else {
echo 'Hubo un error.';
}
?>
Note: If any line in your message is longer than 70 characters, wordwrap()
should be used. An example: $mensaje = wordwrap($mensaje, 70, "\r\n");
Manual mail ()
PHPMailer
Let's see an alternative, without the need to install a mail server.
We include the PHPMailer
library ( download from GitHib ):
//Importar clases de PHPMailer en el espacio de nombres global.
use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
We compose our mail:
//Nueva instancia de PHPMailer.
$mail = new PHPMailer;
//Caracteres utf-8.
$mail->CharSet = 'UTF-8';
//Usar SMTP.
$mail->isSMTP();
//Habilitar la depuración de SMTP:
// 0 = off (Usar en producción)
// 1 = Mensaje cliente
// 2 = Mensaje cliente y servidor
$mail->SMTPDebug = 2;
//Nombre de host del servidor de correo.
$mail->Host = 'smtp.gmail.com';
// Usar
// $mail->Host = gethostbyname('smtp.gmail.com');
// Si su red no admite SMTP sobre IPv6
// Establezca el número de puerto SMTP - 587 para TLS autenticado, a.k.a. RFC4409 SMTP submission.
$mail->Port = 587;
//Sistema de encriptación para usar - ssl (obsoleto) o tls.
$mail->SMTPSecure = 'tls';
//Si se debe usar la autenticación SMTP.
$mail->SMTPAuth = true;
//Tu usuario Gmail.
$mail->Username = "[email protected]";
//Contraseña de tu cuenta.
$mail->Password = "xxxxxxxx";
//Desde (from).
$mail->setFrom('[email protected]', 'Nombre');
//Dirección de respuesta alternativa.
$mail->addReplyTo('[email protected]', 'First Last');
//Destino (to).
$mail->addAddress('[email protected]', 'Daniel');
//Título del correo electrónico a enviar.
$mail->Subject = 'Soy el titulo';
//Leer un cuerpo de mensaje HTML desde un archivo externo, convertir imágenes referenciadas a incrustadas,
//convertir HTML en un cuerpo alternativo básico de texto plano
$mail->msgHTML("Tu cuerpo HTML");
//Envíe el mensaje, revise si hay errores.
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo 'Tu mensaje fue enviado.';
}
GitHub Source
Note: I want to remind you that our Gmail
account works with PHPMailer
, you have to Activate access to less secure applications .
Change access to the account for less secure apps
To keep your Google accounts of work, school or another group more protected, we block less secure applications so they can not access them. If you have an account of this type, you will be shown the error "Incorrect password" when you try to login. If so, you have two options:
- Option 1: install a more secure application that uses measures of
more solid security. All Google products, like Gmail,
They use the most recent security measures.
- Option 2: change the settings to allow applications
less secure access your account. This option is not recommended
because it can facilitate access to your account to another person. Yes
Do you want to allow it anyway, follow these steps:
Go to the less secure apps section of your Google account.
Enable Allow access for less secure applications. If you do not see this setting, the administrator may have disabled
the access of less secure applications to the account.