Phpmailer not taking form value

Asked

Viewed 79 times

-2

So, I have an example registration form to test Phpmailer, only that PHP is not accepting the form ID shows the error:

Undefined index

HTML and PHP are just below:

<?php

//ATENÇÃO ESSE TIPO DE ENVIO SOMENTE PARA USO DO GMAIL
//PARA USOS DE OUTROS DOMINIOS UTILIZA-SE OUTRAS CONFIGURAÇÕES

//pegando valores do FORMULARIO DE CONTATO
$nome       = $_POST ["nome"];
$email      = $_POST ["email"];
$mensagem   = $_POST ["mensagem"];

// Importando as Clases do PHPMailer

include("phpmailer\src\class.phpmailer.php");

require 'phpmailer\src\PHPMailerAutoload.php';


$mail = new PHPMailer(true);                              // Passando "true" para o nova class $mail
try {
    //CONFIGURAÇÕES DO SERVER
    $mail->SMTPDebug = 2;                                 // Habilitando
    $mail->isSMTP();                                      // setando o  SMTP
    $mail->Host = 'smtp.gmail.com';                       // Especificando o endereço e o tipo de SMTP servers
    $mail->SMTPAuth = true;                               // Habilitando
    $mail->Username = 'samuel******[email protected]';                 // SMTP e-mail do GMAIL
    $mail->Password = '*********';                           // SENHA DO GMAIL
    $mail->SMTPSecure = 'tls';                            // Habilitando o tipo de criptografia tls
    $mail->Port = 587;                                      // Conectando a porta TCP   

    //E-MAILS RECIPIENTES
    $mail->setFrom('[email protected]', 'Usuario');  
    $mail->addAddress('$email); 

    //CONTEÚDO
    $mail->isHTML(true);                                  // Setando o e-mail para formato HMTL
    $mail->Subject = 'Teste PHPMailer';
    $mail->Body    = 'Essa é uma Mesangem de Teste <b>in bold!</b>';
    $mail->AltBody = 'O corpo deste e-mail esta em formato HTML';

    $mail->send();
    echo 'Mensagem Enviada com Sucesso!';
} catch (Exception $e) {
    echo 'Mensagem não enviada. Erro: ', $mail->ErrorInfo;
}
<!DOCTYPE html>
<html>
    <head>
        <title> Teste de envio dos dados </title>
    </head>
    <body>
        <h4 align="center"> Formulário de Contato </h4>
            <form action="index.php" method="post" align="center">
            <br>
            <div>
                <label>NOME</label>
                <input type="text" id="nome">
            </div>
            <br>
            <div>
                <label>E-MAIL</label>
                <input type="text" id="email">
            </div>
            <br>
            <div>
                <label>MENSAGEM</label>
            </div>
            <textarea rows="10" cols="30" id="mensagem"></textarea>
            <br><br>

            <input type="submit">
        </form>
    </body>
</html>
  • thanks for your attention, but it didn’t work

  • 1

    $mail->addAddress('$email); Missing close the simple quotes here

  • this giving invalid email

  • So that means you don’t even need the quotes. Just the actual variable

  • even so it continues, but I think the problem is that not taking the values of the ID in the Form

2 answers

2

Corrections

The way it was, it wouldn’t work because of space, because $_POST is a Array and that way you’re wrong: $_POST ["nome"];

To correct I traded for filter_input thus helps against SQL Injection:

$nome = filter_input(POST, 'nome');

I added the extra properties to the SMTP, because depending on your server, you can avoid certain errors:

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )   
);

I commented on the line # $mail->AltBody = 'O corpo ...'; because as you are using $mail->isHTML(true); then you’ll only need the $mail->Body.

Contrary to what is written O corpo deste e-mail esta em formato HTML, would be "...NAY is in HTML".

And on the part of HTML, was missing the attribute name in their inputs, correcting by staying:

<input type="text" name="nome">
<input type="text" name="email">
<textarea rows="10" cols="30" name="mensagem">

*as stated by @fernandosavio, you can also keep the attribute id, if use, if not, better take since it has no use.


Final script

$nome     = filter_input(POST, 'nome');
$email    = filter_input(POST, 'email');
$mensagem = filter_input(POST, 'mensagem');

include 'phpmailer\src\class.phpmailer.php';
require 'phpmailer\src\PHPMailerAutoload.php';

$mail = new PHPMailer(true);                              
try {
    $mail->SMTPDebug = 2;  
    $mail->isSMTP(); 
    $mail->Host = 'smtp.gmail.com';    
    $mail->SMTPAuth = true;
    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )    
    );
    $mail->Username = 'samuel******[email protected]';    
    $mail->Password = '*********';               
    $mail->SMTPSecure = 'tls'; 
    $mail->Port = 587; 
    $mail->setFrom('[email protected]', 'Usuario');  
    $mail->addAddress('$email'); 

    $mail->isHTML(true);
    $mail->Subject = 'Teste PHPMailer';
    $mail->Body    = 'Essa é uma Mesangem de Teste <b>in bold!</b>';
    # $mail->AltBody = 'O corpo deste e-mail esta em formato HTML';

    $mail->send();
    echo 'Mensagem Enviada com Sucesso!';

} catch (Exception $e) {

    echo 'Mensagem não enviada. Erro: ', $mail->ErrorInfo;
}

<!DOCTYPE html>
<html>
    <head>
        <title> Teste de envio dos dados </title>
    </head>
    <body>
        <h4 align="center"> Formulário de Contato </h4>
            <form action="index.php" method="post" align="center">
            <br>
            <div>
                <label>NOME</label>
                <input type="text" name="nome">
            </div>
            <br>
            <div>
                <label>E-MAIL</label>
                <input type="text" name="email">
            </div>
            <br>
            <div>
                <label>MENSAGEM</label>
            </div>
            <textarea rows="10" cols="30" name="mensagem"></textarea>
            <br><br>

            <input type="submit">
        </form>
    </body>
</html>
  • Thank you very much I changed the Code and I changed what the fernandosavio said and it worked Perfectly

  • @Samuelnicolau For nothing! .... But by site rules, it is not necessary to thank. Your vote on the answer would already be for this purpose. Don’t forget to mark an answer to finalize the question!

  • I’m aware now!

1


The names of a input passed in a POST is defined by the attribute name and not by the attribute id.

The attribute id is an identifier within the document, but this identifier is not sent in requests, but rather the attribute name and its value (value).

Then your inputs would change:

 <input type="text" id="nome">

for:

 <input type="text" name="nome">
  • Thank you very much, it worked !!

  • For nothing. Do not forget that it is not necessary to remove the id, the two fields can coexist and have the same value if necessary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.