Do not send emails through my form

6

I make a form to send an email with the filling of my form, but it only marks me error of echo of shipment, I do not know what I am doing wrong.

This is my form:

</head>

<body>

<form name="formulario_contacto" method="post" action="Enviar_mail.php">
<table width="500px">
<tr>
<td>
<label for="nombre">Nombre: *</label>
</td>
<td>
<input type="text" name="nombre" maxlength="50" size="25">
</td>
</tr>


<tr>
<td valign="top">
<label for="apellido">Apellido: *</label>
</td>
<td>
<input type="text" name="apellido" maxlength="50" size="25">
</td>
</tr>


<tr>
<td>
<label for="email">Dirección de E-mail: *</label>
</td>
<td>
<input type="text" name="email" maxlength="80" size="35">
</td>
</tr>


<tr>
<td>
<label for="tfno">Número de teléfono:</label>
</td>
<td>
<input type="text" name="tfno" maxlength="25" size="15">
</td>
</tr>


<tr>
  <td>Asunto:</td>
  <td><label for="asunto"></label>
    <input type="text" name="asunto" id="asunto"></td>
</tr>


<tr>
<td>
<label for="comments">Comentarios: *</label>
</td>
<td>
<textarea name="comments" maxlength="500" cols="30" rows="5"></textarea>
</td>
</tr>


<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Enviar">
</td>
</tr>


</table>
</form>




</body>
</html>

This is my PHP code

<?php

 $texto_mail=$_POST["comments"];

 $destinatario=$_POST["email"];

 $asunto=$_POST["asunto"];

 $headers="MIME-Version: 1.0\r\n ";

 $headers.="Content-type: text\html;charset=iso-8859-1\r\n";

 $headers.= "From: Prueba Juan <[email protected]>\r\n";

 $exito=mail($destinatario, $asunto, $texto_mail, $headers);

 if ($exito){

     echo"Mensaje  enviado con exito"; 

 }
    else

 {


     echo"Error de envio";
 }




?>
    
asked by Carlos 29.05.2018 в 18:35
source

4 answers

12

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.
answered by 09.09.2018 в 20:24
5

Bearing in mind that the mail () function does not have a return value that allows us to debug in case of error, a suggestion is to use the error_get_last () function when mail () fails (returns false). For example,

$exito = mail('[email protected]', 'Noticias', $mensaje);
if (!$exito) {
    $mensajeError = error_get_last()['message'];
}

Credit: stackoverflow in English

  

Important: It should be clarified, according to the comments to this answer, that this could be   be only valid for Windows.

    
answered by 08.09.2018 в 03:54
4
<?php
$destino= "[email protected]";
$contacto="Xeoms";
$nombre=$_POST["nombre"];
$email=$_POST["email"];
$mensaje = $_POST["mensaje"]; 
$contenido = "nombre :". $nombre . "\nCorreo :" . $email . "\nmensaje :" . $mensaje;
mail($destino, "contacto", $contenido);
header("Location:contacto.html");

?>

here is an example of how to send mail. It only works in a hosting

    
answered by 29.05.2018 в 22:03
4

First of all, you have to verify that your server is capable of sending emails through the PHP mail function, which is not usually configured by default in local servers such as LAMP, XAMPP, WAMP, MAMP, ...

Another thing, some hosting such as GoDaddy, have many problems when using the PHP mail function (emails do not usually arrive or are marked as SPAM).

To avoid this kind of problems you could use PHPMailer , it's simple to use, object oriented and in the link you can find several very good examples.

And in case you want to continue using mail I recommend changing your code in this section for the following:

 if ( mail($destinatario, $asunto, $texto_mail, $headers) ) {
     #Envío correcto ...
 } else {
     #Error ...
 }

Your code will be more readable and you will save a few lines of code.

    
answered by 09.09.2018 в 04:07