Query about PHPMAILER

3

I wanted to know if the PHP setup I'm doing for the submission in a form is well-armed. From what I read in the documentation I have to download two PHP files, the Class.phpmailer.php and the SMTP.php and link them the way I'm doing with a require, both files are in the same root where the shipment would be. php that the file that I write below. On the other hand, I do not have a clear idea of what kind of data I need to have from the client so that the data reaches their account. In this example I'm doing with data from my hotmail account to do those tests.

On the other hand I'm doing a script where I link the PHP file through Ajax I wanted to know if it is correctly armed.

<?php
function envioMail(){

$ecommerce = $_POST["Ecommerce"];
$nombre = $_POST["Nombre"];
$telefono = $_POST["Telefono"];
$email = $_POST["Email"];

require("class.phpmailer.php");
require("SMTP.php");
require("Exception.php");

$mail = new PHPMailer(true);

$mail->Mailer = "smtp";
$mail->SMTPAuth = true;
$mail->Host = "smtp.live.com"; // A RELLENAR. Aquí pondremos el SMTP a utilizar. Por ej. mail.midominio.com smtp.gmail.com
$mail->Username = "[email protected]"; // A RELLENAR. Email de la cuenta de correo. [email protected] La cuenta de correo debe ser creada previamente. 
$mail->Password = ""; // A RELLENAR. Aqui pondremos la contraseña de la cuenta de correo
$mail->From = "[email protected]";  // A RELLENAR Desde donde enviamos (Para mostrar). Puede ser el mismo que el email creado previamente.
$mail->FromName = "Mariano"; //A RELLENAR Nombre a mostrar del remitente. 
$mail->Subject = "Mensaje de Welivery"; // Este es el titulo del email.
$mail->AddAddress("[email protected]");/*email de CM*/

$body  = 
"
Se ha informado la descarga del siguiente resultado: $codigoAlerta

Muchas gracias

Equipo PfAst
Pfizer
"; 
$mail->Body = $body;
$mail->CharSet = 'UTF-8';
$mail->Send();

}
if($_POST){
switch($_POST["tarea"]){
case "envio":envioMail();break;
}
}
?>
$(function(){ 

  var errorMessage  = $(".errorMessage");
  var validMessage  = $(".validMessage");
  
  function clearInputs(){
    errorMessage.html("");
    validMessage.html("");
  }
  $(".inputValidation").on("click", function(e){
      clearInputs();
  });


  $("#btnSubmit").on("click", function(e){
    clearInputs();
    var hasError = false;
    var hasvalid = true;
    var exprMail= /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
    $(".inputValidation").each(function(){
        var $this = $(this);

        if($this.attr("name") === "email"){
          if( !(exprMail.test($this.val()) ) ) {
            hasError = true;

            $this.addClass("inputError");
            errorMessage.html("<p>Por favor, ingrese un email valido.</p>");
            e.preventDefault();
          }
        }


        if($this.val() == ""){
          hasError = true;

          $this.addClass("inputError");
          errorMessage.html("<p>Por favor, complete los siguientes campos.</p>");
          e.preventDefault();
        }

        if($this.val() != ""){
          $this.removeClass("inputError"); 

        }else{
          return true; 
        }
        
      });      

      errorMessage.slideDown(700);

      if(hasError == false){
          Ecommerce = document.getElementById("exampleInputEcommerce").value;
          Nombre = document.getElementById("exampleInputNombre").value;
          Telefono = document.getElementById("exampleInputPhone").value;
          Email = document.getElementById("exampleInputEmail1").value; 
          data2= { 
              ecommerce:Ecommerce,
              nombre:Nombre,
              telefono:Telefono,
              email:Email,
              tarea: "envio"
            };

          $.ajax({
            type: "POST",
            url:"envio.php",
            data: data2,
            success:function(data){
              
              /*$('#respuesta').fadeOut('fast').html(
                "Gracias, se a enviado su mensaje"
              );*/

            },
            
            error: function(XMLHttpRequest, textStatus, errorThrown) { 
              $('.validMessage').fadeOut('fast').html(
                "Gracias, se a enviado su mensaje"
              );
              $(".inputValidation").val("");
            } 

          });

      }

  }); //Form .submit
});
    
asked by Mariano Andres Franco 16.11.2018 в 20:45
source

3 answers

3

to give you a hand I leave the settings I use in PHPMAILER to build an email with information obtained from the database, using templates and sending the email with embedded images:

UPDATE: If you are going to use a GMAIL email, you have to enter the gmail settings and modify everything related to more secure applications:

link

  • Log in with your administrator account.

  • Click on Security > Basic configuration.

  • In Unsecured Applications, select Access settings for insecure applications.

  • In the secondary window, activate the option Allow users to manage their access to unsafe applications.

  • Once you have enabled this option, the users of the group or organizational unit to which it is applied can allow or prevent access for unsafe applications.

PhpMailer documentation on GitHub:

link

Required files

require '../core/mail/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;

In this example I bring information from the database to fill in variables and customize the mail

$detalleReporte = MvcControllerBug::reporteModel("bugreport bu", 
$_SESSION["idUsuario"]);
$fechaReporte = $detalleReporte[0];
$detalleBug = $detalleReporte[1];
$direccionReporte = $detalleReporte[2];
$mailUsuario = $detalleReporte[3];
$nombreUserMail = $_SESSION['nombre']." ".$_SESSION['apellido'];
$fechaFinal=date("d-m-Y H:i:s",strtotime($fechaReporte));
$detalleFinal = "<b><li>Fecha de generacion de reporte: </b> ".$fechaFinal."</li><li> 
<b>Detalle cargado por
el usuario: </b>".$detalleBug."</li><li><b>Pagina desde donde se envio la 
Sugerencia / Bug / Reporte: </b>".$direccionReporte."</li>
<li><b>Mail del usuario: </b>".$mailUsuario."</li>";
$nombreApellido = $_SESSION['nombre']." ".$_SESSION['apellido'];

Here begins the mail

$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = gethostbyname('NOMBRE DEL HOST');
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = "MAIL DESDE DONDE SALE EL CORREO";
$mail->Password = "CONTRASEÑA DE ESE MAIL";
$mail->setFrom('MAIL DESDE DONDE VA A DECIR QUE SALIO', 'NOMBRE');
$mail->addReplyTo('MAIL A DONDE SE PUEDE RESPONDER', 'NOMBRE');
$mail->addBcc('MAILS OCULTOS A LOS QUE SE VA A ENVIAR TAMBIEN', 'NOMBRE');
$mail->addBcc('MAILS OCULTOS A LOS QUE SE VA A ENVIAR TAMBIEN', 'NOMBRE');
$mail->addBcc('MAILS OCULTOS A LOS QUE SE VA A ENVIAR TAMBIEN', 'NOMBRE');

Here is the email to whom you are going to send plus the name of that person, in this case I have variables because I declared them above:

$mail->addAddress($mailUsuario, $nombreUserMail);

You can embed images in the mail by calling them in this way, you will need a template of how you want to see the mail, a few lines below I'll call you and I'll give you an example:

$mail->AddEmbeddedImage('../core/mail/mail.jpg', '1200_600');
$mail->AddEmbeddedImage('../core/mail/footer.jpg', 'footer');

When you see the template avs to see that the images are declared here and in the template are called this way:

src="cid:1200_600"

Title of the mail, use the variables that you declare above to personalize it:

$mail->Subject = "Reporte ".$_SESSION['nombre']." ".$_SESSION['apellido']."  Nueva Sugerencia"; 

I call the template that arms as you will see the mail:

$shtml = file_get_contents('../core/mail/template.html');

Body of the mail with variables declared above, check that it passes through the variable $ shtml that is the template

Notice this line: I above declare a variable $ finalFinal that has what the user will read in the body of the mail, in this line specifies what it does is go to the template and look for the id="message" and that element puts the $ finalFinal to see, is like the images, you declare everything here and dsp what you put into the template:

$cuerpo = str_replace('<i id="mensaje"></i>',  $detalleFinal, $shtml);
$mail->Body = $cuerpo;
$mail->AltBody = 'This is a plain-text message body';   

I finish by sending the mail

$mail->send();

TEMPLATE:

You can download different models from this page:

link

Once you do it, you only erase what does not work for you and you adapt it to your information.

<!DOCTYPE html>
            <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="x-apple-disable-message-reformatting">
            </head>
            <body>
                <center>
                    <table align="center" role="presentation" cellspacing="0" cellpadding="0" border="0" width="600" style="margin: 0 auto;" class="email-container" style="box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2); transition: 0.3s; width: 40%;">
                        <tr>
                            <td style="background-color: #ffffff;">
                                <img src="cid:1200_600" width="900" height="" alt="alt_text" border="0" style="width: 100%; max-width: 900px; height: auto; background: #dddddd; font-family: sans-serif; font-size: 15px; line-height: 15px; margin: auto;" class="g-img">
                            </td>
                        </tr>
                        <tr style="padding: 40px 0; text-align: center">
                            </tr>
                        <tr>
                            <td style="background-color: #ffffff;">
                                <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
                                    <tr>
                                        <td style="padding: 30px; font-family: sans-serif; font-size: 15px; line-height: 20px; color: #555555;">
                                            <h1 style="margin: 0 0 10px; font-size: 25px; line-height: 30px; color: #333333; font-weight: normal;">Nuevo Reporte</h1>
                                            <br>
                                            <ul style="padding: 0; margin: 0; list-style-type: disc;">
                                                <i id="mensaje"></i>
                                            </ul>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr style="padding: 40px 0; text-align: center">
                            </tr>
                        <tr>
                            <td style="background-color: #ffffff;">
                                <img src="cid:footer" width="900" height="" alt="alt_text" border="0" style="width: 100%; max-width: 900px; height: auto; background: #dddddd; font-family: sans-serif; font-size: 15px; line-height: 15px; margin: auto;" class="g-img">
                            </td>
                        </tr>
                    </table>
                </center>
            </body>
            </html>

And the mail would arrive more or less like this:

To show a message if the mail came out or I do not do the following:

For that use sweetalert:

link

You need Jquery too: link

You download the file or use the CDN:

Now valid, if the mail came out I show a message and if not an error. In this case in my code I have a variable called redirection because there I will go to where I will send it once the user closes the notification or closes itself after 1.5 sec.

        if (!$mail->send()) {
            echo '<script>swal("Error al enviar el reporte", 
            "Ocurrio un error durante la generacion del reporte", "error", 
            {closeOnClickOutside: false, closeOnEsc: false, timer: 1500}).then((value) => {
            window.location.replace("'.$redireccionamiento.'");
            });</script>'; 
        } else {
             echo '<script>swal("Mail enviado con exito", 
            "Ya recibimos tu consulta, muchas gracias.", "success", 
            {closeOnClickOutside: false, closeOnEsc: false, timer: 1500}).then((value) => {
            window.location.replace("'.$redireccionamiento.'");
            });</script>'; 
        }

    
answered by 16.11.2018 в 21:15
0

Query, I am wanting to generate that when the fields of the form are completed and the sending is made the user can receive some type of message that they will contact him, the problem is that I do not know if I am generant the php file with the answer

$(function(){ 

  var errorMessage  = $(".errorMessage");
  var validMessage  = $(".validMessage");
  
  function clearInputs(){
    errorMessage.html("");
    validMessage.html("");
  }
  $(".inputValidation").on("click", function(e){
      clearInputs();
  });


  $("#btnSubmit").on("click", function(e){
    clearInputs();
    var hasError = false;
    var hasvalid = true;
    var exprMail= /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
    $(".inputValidation").each(function(){
        var $this = $(this);

        if($this.attr("name") === "email"){
          if( !(exprMail.test($this.val()) ) ) {
            hasError = true;

            $this.addClass("inputError");
            errorMessage.html("<p>Por favor, ingrese un email valido.</p>");
            errorMessage.slideDown(700);
            e.preventDefault();
          }
        }


        if($this.val() == ""){
          hasError = true;

          $this.addClass("inputError");
          errorMessage.html("<p>Por favor, complete los siguientes campos.</p>");
          errorMessage.slideDown(700);
          e.preventDefault();
        }

        if($this.val() != ""){
          $this.removeClass("inputError"); 

        }else{
          return true; 
        }
        
      }); //Input
     

  /*
    $(".inputValidation").each(function(){
      var $this = $(this);

      if($this.val() == ""){
        hasvalid = false;
        $this.addClass("inputError");
        validMessage.html("<p>Por favor, complete los siguientes campos.</p>");
        e.preventDefault();
      }if($this.val() != ""){
        $this.removeClass("inputError"); 

      }else{
        return true; 
        }

      }); //Input
    validMessage.slideDown(700);*/

      /*ajax*/
      if(hasError == false){
       $.ajax({
              type: 'POST', 
              url:'envio.php',
              dataType:'json', 
              data: $('#form_step1').serialize(),
  	          success:function(response){
                console.log("estoy en el ajax");
                console.log(response);
                $('.validMessage').fadeOut('fast').html(
                  "Gracias, se a enviado su mensaje"
                );
                $(".inputValidation").val("");
                /*$('#respuesta').fadeOut('fast').html(
                  "Gracias, se a enviado su mensaje"
                );*/
               
              },
      		    error: function (jqXHR, textStatus, errorThrown) {
      		    } 

            });

        }




  }); //Form .submit
});

<?php
//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Argentina/Buenos_Aires');

if ((isset($_POST['ecommerce']) && $_POST['ecommerce'] != "") &&
	(isset($_POST['nombre']) && $_POST['nombre'] != "") &&
	(isset($_POST['telefono']) && $_POST['telefono']!= "" ) &&
	(isset($_POST['email']) && $_POST['email']!= "") &&
	(isset($_POST['envio']) && $_POST['envio'] === 'envio')  ){

 
	require_once('mailer/class.phpmailer.php');

	
	$ecommerce = $_POST["ecommerce"];
	$nombre = $_POST["nombre"];
	$telefono = $_POST["telefono"];
	$email = $_POST["email"];
	$envio = $_POST['envio'];


	$body  = 
	"
	Datos enviados por el usuario desde el Formulario de contacto: 
	
	$ecommerce
	$nombre
	$telefono
	$email

	"; 
	
	$mail = new PHPMailer();
	$mail->IsSMTP();
	$mail->CharSet = 'UTF-8';
	$mail->Host = "smtp.live.com"; // saber que tipo de cuenta.
	$mail->SMTPAuth= true;
	$mail->Port = 587;
	$mail->Username= "[email protected]"; // su cuenta de correo
	$mail->Password= "marianoandres17"; // su contraseña 
	$mail->SMTPSecure = 'tls';
	$mail->From = "[email protected]"; // su cuenta
	$mail->FromName= "";
	$mail->isHTML(true);
	$mail->Subject ="Mensaje de Welivery";
	$mail->Body =$body;

	$address = "[email protected]"; // 
	$mail->addAddress($address);

	if (!$mail->send()) {
	    $output = json_encode(array('type' => 'error', 'text' => 'Error - Comuniquese con el Administrador de la pagina '));
	    die($output);
	} else {
	    $output = json_encode(array('type' => 'message', 'text' => 'Tu mensaje se ha enviado correctamente. A la brevedad nos contactaremos. Muchas gracias'));
	    die($output);
	}

	
	$ecommerce = $_POST["ecommerce"];
	$nombre = $_POST["nombre"];
	$telefono = $_POST["telefono"];
	$email = $_POST["email"];
	$envio = $_POST['envio'];


	$body  = 
	"
	En brevedad nos estaremos comunicando.

	Muchas Gracias!

	"; 
	
	$mail = new PHPMailer();
	$mail->IsSMTP();
	$mail->CharSet = 'UTF-8';
	$mail->Host = "smtp.live.com"; // saber que tipo de cuenta.
	$mail->SMTPAuth= true;
	$mail->Port = 587;
	$mail->Username= "[email protected]"; // su cuenta de correo
	$mail->Password= ""; // su contraseña 
	$mail->SMTPSecure = 'tls';
	$mail->From = "[email protected]"; // su cuenta
	$mail->FromName= "Mariano";
	$mail->isHTML(true);
	$mail->Subject ="Respuesta de Formulario Welivery";
	$mail->Body =$body;

	// $address = $email; // 
	$mail->addAddress($email);

	if (!$mail->send()) {
	    $output = json_encode(array('type' => 'error', 'text' => 'Error - Comuniquese con el Administrador de la pagina '));
	    die($output);
	} else {
	    $output = json_encode(array('type' => 'message', 'text' => 'Tu mensaje se ha enviado correctamente. A la brevedad nos contactaremos. Muchas gracias'));
	    die($output);
	}



} else {
    $output = json_encode(array('type' => 'message', 'text' =>'No se pudo enviar el email, asegurese que el email exista!!!'));
    die($output);
}
    
answered by 22.11.2018 в 01:36
-1

<?php
//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Argentina/Buenos_Aires');

if ((isset($_POST['ecommerce']) && $_POST['ecommerce'] != "") &&
	(isset($_POST['nombre']) && $_POST['nombre'] != "") &&
	(isset($_POST['telefono']) && $_POST['telefono']!= "" ) &&
	(isset($_POST['email']) && $_POST['email']!= "") &&
	(isset($_POST['envio']) && $_POST['envio'] === 'envio')  ){

 
	require_once('mailer/class.phpmailer.php');


	//MAtest2018.01@gmail   MAtest201801!
	$emailCliente = "[email protected]";
	$passwordCliente = "xxxx";
	
	$fromCliente = $emailCliente;


	$ecommerce = $_POST["ecommerce"];
	$nombre = $_POST["nombre"];
	$telefono = $_POST["telefono"];
	$email = $_POST["email"];
	$envio =  $_POST['envio'];
	$address = $email;

	$body  = 
	"
	Datos enviados por el usuario desde el Formulario de contacto: <br/> 
	
	<strong>Ecommerce:</strong> $ecommerce <br/>
	<strong>Nombre y Apellido:</strong> $nombre <br/>
	<strong>Teléfono:</strong> $telefono <br/>
	<strong>Email:</strong> $email <br/>

	"; 
	
	$mail = new PHPMailer();
	$mail->IsSMTP();
	$mail->CharSet = 'UTF-8';
	$mail->Host = "smtp.gmail.com"; // saber que tipo de cuenta.
	$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
	$mail->SMTPAuth= true;
	$mail->Port = 587;
	$mail->Username= $emailCliente; // su cuenta de correo
	$mail->Password= $passwordCliente; // su contraseña 
	$mail->From = $emailCliente; // su cuenta
	$mail->FromName= "Welivery";
	$mail->isHTML(true);
	$mail->Subject ="Mensaje de Welivery";
	$mail->Body = $body;

	$mail->addAddress("[email protected]", $nombre);

	if (!$mail->send()) {
	    $output = json_encode(array('type' => 'error', 'text' => 'Error - Comuniquese con el Administrador de la pagina '));
	    die($output);
	} else {
	    $output = json_encode(array('type' => 'message', 'text' => 'Tu mensaje se ha enviado correctamente. A la brevedad nos contactaremos. Muchas gracias'));
	    die($output);
	}

	/*
	$ecommerce = $_POST["ecommerce"];
	$nombre = $_POST["nombre"];
	$telefono = $_POST["telefono"];
	$email = $_POST["email"];
	$envio = $_POST['envio'];


	$body  = 
	"
	En brevedad nos estaremos comunicando.

	Muchas Gracias!

	"; 
	
	$mail = new PHPMailer();
	$mail->IsSMTP();
	$mail->CharSet = 'UTF-8';
	$mail->Host = "smtp.gmail.com"; // saber que tipo de cuenta.
	$mail->SMTPAuth= true;
	$mail->Port = 587;
	$mail->Username= "[email protected]"; // su cuenta de correo
	$mail->Password= "marianoandres"; // su contraseña 
	$mail->SMTPSecure = 'tls';
	$mail->From = "[email protected]"; // su cuenta
	$mail->FromName= "Welivery";
	$mail->isHTML(true);
	$mail->Subject ="Mensaje de Welivery";
	$mail->Body =$body;

	// $address = $email; // 
	$mail->addAddress($email);

	if (!$mail->send()) {
	    $output = json_encode(array('type' => 'error', 'text' => 'Error - Comuniquese con el Administrador de la pagina '));
	    die($output);
	} else {
	    $output = json_encode(array('type' => 'message', 'text' => 'Tu mensaje se ha enviado correctamente. A la brevedad nos contactaremos. Muchas gracias'));
	    die($output);
	}*/



} else {
    $output = json_encode(array('type' => 'message', 'text' =>'No se pudo enviar el email, asegurese que el email exista!!!'));
    die($output);
}
    
answered by 29.11.2018 в 16:57