How to condition email sending content with a chosen variable in the form?

Asked

Viewed 34 times

0

I am trying to condition the email sending format by to a certain option chosen by the user, in the Subject / Script : If the option is SCRIPT, the contents of the $html variable will be sent. If it is INFORMATION, the contents of the $html2 variable will be sent.

I’m making some attempts with If/Else and Switch but I’m having syntax problems.

Below is the index code and the email sending php.

Thanks in advance.

index php.

<!DOCTYPE html>

<html lang="pt">


<head>
    <title>Formulário xxxx</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/png" href="images/icons/favicon.ico"/>

    <!--========================================== IMPORTAÇÕES CSS ====================================================-->
    <link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
    <link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css">
    <link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css">
    <link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css">
    <link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css">
    <link rel="stylesheet" type="text/css" href="css/util.css">
    <link rel="stylesheet" type="text/css" href="css/main.css">
    <!--========================================== FIM IMPORTAÇÕES CSS=====================================================-->

</head>



    <!--========================================== IMPORTAÇÕES JS =====================================================-->

    <script type="text/javascript">
        function submitForm(action) {
                var form = document.getElementById('form1');
                form.action = action;
                form.submit();
            }
    </script>
    <!--========================================== FIM IMPORTAÇÕES JS =====================================================-->

<body>
<body>

    <div class="container-contact100">
        <div class="wrap-contact100">
            <form class="contact100-form validate-form" enctype="multipart/form-data" method="POST" action="gravar_enviar.php">
                <span class="contact100-form-title">
                    Demandas xxxxxx
                </span>

                <div class="wrap-input100 validate-input" data-validate="Campo Obrigatório">
                    <span class="label-input100">Data</span>
                    <input class="input100" type="text" name="Datas" placeholder="Formato DD/MM/AAAA">
                    <span class="focus-input100"></span>
                </div>

                <div class="wrap-input100 validate-input" data-validate = "Campo Obrigatório">
                    <span class="label-input100">Módulo</span>
                    <input class="input100" type="text" name="Modulo" placeholder="Especifique o módulo">
                    <span class="focus-input100"></span>
                </div>

                <div class="wrap-input100 validate-input" data-validate = "Campo Obrigatório">
                    <span class="label-input100">Assunto / Script</span>
                    <input class="input100" type="text" name="AssuntoScript" placeholder="Especifique qual assunto/script">
                    <span class="focus-input100"></span>
                </div>

                <div class="wrap-input100 validate-input" data-validate = "Campo Obrigatório">
                    <span class="label-input100">Descrição da Alteração</span>
                    <textarea class="input100" name="DescricaoAlteracao" placeholder="Descreva quais foram as modificações"></textarea>
                    <span class="focus-input100"></span>
                </div>

                <div class="wrap-input100 input100-select">
                    <span class="label-input100">Script ou Informação?</span>
                    <div>
                        <select class="selection-2" name="ScriptInformacao">
                            <option>Selecione</option>
                            <option>Script</option>
                            <option>Informação</option>
                        </select>
                    </div>
                    <span class="focus-input100"></span>
                </div>


                <div class="wrap-input100 input100-select">
                    <span class="label-input100">Responsável</span>
                    <div>
                        <select class="selection-2" name="Responsavel">
                            <option>Selecione</option>
                            <option>Adriana</option>
                            <option>Fernanda</option>
                        </select>
                    </div>
                    <span class="focus-input100"></span>
                </div>

                <div class="wrap-input100 input100-select">
                    <span class="label-input100">Tipo</span>
                    <div>
                        <select class="selection-2" name="Tipo">
                            <option>Selecione</option>
                            <option>Alteração</option>
                            <option>Inclusão</option>
                            <option>Exclusão</option>
                            <option>Melhoria</option>
                            <option>Incidente</option>
                            <option>Comunicado</option>
                            <option>Atualização</option>
                            <option>Campanha</option>
                        </select>
                    </div>
                    <span class="focus-input100"></span>
                </div>


                <div class="wrap-input100 input100-select">
                    <span class="label-input100">Origem</span>
                    <div>
                        <select class="selection-2" name="Origem">
                            <option>Selecione</option>
                            <option>Cerat</option>
                            <option>Geate</option>
                            <option>Tivit</option>

                        </select>
                    </div>
                    <span class="focus-input100"></span>
                </div>


            <div class="wrap-input100 input100-select">
                    <span class="label-input100">Anexar</span>
                        <input type="file" id="arquivo" name="arquivo" value="Anexar">
                    <span class="focus-input100"></span>
                </div> 


                <div class="container-contact100-form-btn">
                    <div class="wrap-contact100-form-btn">
                        <div class="contact100-form-bgbtn"></div>
                        <button class="contact100-form-btn" type="submit">
                            <span>
                                Enviar
                                <i aria-hidden="false" ></i>
                            </span>
                        </button>
                    </div>
                </div>


            <a href="gerarexcel.php">
                    <div class="container-contact100-form-btn">
                    <div class="wrap-contact100-form-btn">
                        <div class="contact100-form-bgbtn"></div>

                        <span class="contact100-form-btn">
                                Gerar Planilha do Mês Atual
                                <i aria-hidden="false"></i>
                            </span>

                    </div>
                </div></a>


            </form>
        </div>
    </div>



    <div id="dropDownSelect1"></div>

    <!--========================================== IMPORTAÇÕES JS =====================================================-->

    <script src="vendor/jquery/jquery-3.2.1.min.js"></script>
    <script src="vendor/animsition/js/animsition.min.js"></script>
    <script src="vendor/bootstrap/js/popper.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.min.js"></script>
    <script src="vendor/select2/select2.min.js"></script>
    <script>
        $(".selection-2").select2({
            minimumResultsForSearch: 20,
            dropdownParent: $('#dropDownSelect1')
        });
    </script>
    <script src="vendor/daterangepicker/moment.min.js"></script>
    <script src="vendor/daterangepicker/daterangepicker.js"></script>
    <script src="vendor/countdowntime/countdowntime.js"></script>
    <script src="js/main.js"></script>

    <!--========================================== FIM IMPORTAÇÕES JS =====================================================-->


</body>
</html>

gravar_enviar.php

<!DOCTYPE html>
<html lang="pt">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Gravado e enviado com sucesso!</title>
</head>

<style>

   Body{
       background: #d9e6fc;
   }


    .msg {
        margin-top:200px;
        font-family: Poppins-Bold;
        width: 100vw;
        font-size: 30px;
        }

</style>

<body>

<center><div class=msg>GRAVADO E ENVIADO COM SUCESSO!<br/><br/>
<a href="index.php">Voltar</a></center></div>

</body>

<?php

echo $msg = '';
if( $_POST ){

    $servidor = 'localhost';
    $usuario = 'xxxxx';
    $senha = 'xxxxx';
    $banco = 'xxxxxx';
    // Conecta-se ao banco de dados MySQL
    $mysqli = new mysqli($servidor, $usuario, $senha, $banco);
    // Caso algo tenha dado errado, exibe uma mensagem de erro
    if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());



    $Datas = $_POST['Datas']; 
    $Modulo = $_POST['Modulo'];
    $AssuntoScript = $_POST['AssuntoScript'];
    $DescricaoAlteracao = $_POST['DescricaoAlteracao'];
    $ScriptInformacao = $_POST['ScriptInformacao'];
    $Responsavel = $_POST['Responsavel']; 
    $Tipo = $_POST['Tipo']; 
    $Origem = $_POST['Origem'];
    $query = "INSERT INTO formulario (Datas, Modulo, AssuntoScript, DescricaoAlteracao, ScriptInformacao, Responsavel, Tipo, Origem)
    VALUES ('".$Datas."', '".$Modulo."', '".$AssuntoScript."', '".$DescricaoAlteracao."', '".$ScriptInformacao."', '".$Responsavel."', '".$Tipo."', '".$Origem."') ";

# $sql = "Update [DB_Daniel].[dbo].[formulario] Set Data = '".$Data."', Modulo = '".$Modulo."', AssuntoScript = '".$AssuntoScript."', DescricaoAlteracao = '".$DescricaoAlteracao."', ScriptInformacao = '".$ScriptInformacao."', Responsavel = '".$Responsavel."', Tipo = '".$Tipo."', Origem = '".$Origem."', Anexos = '".$Anexos."' where id = '".$id."' "; 



    $q = mysqli_query($mysqli,$query);

    if($q){$msg = 'Tudo certo';
} else {
    $msg = 'Deu ruim';
}
}

?>


<!------- ENVIO EMAIL ------------------ !>



<?php


//incluir o phpmailer
require_once("phpMailer/PHPMailerAutoload.php");

//criar instancia do phpmailer
$mail = new PHPMailer();


// Mensagem formatada, enviada no corpo do email =================================================================================

$html = "<!DOCTYPE html>
<html lang='pt'> 
<head> 
<meta charset='UTF-8'>
<style> 
body     {background:#FFFFFF;} 
a, a:link   {color:#5b6105; text-decoration:none;} 
#tab     {margin:0; padding:0px; width:500px; border:1px solid #8F8E96; padding:10px;} 
#tab tr {background:#e3f707; } 
#tab td {color:#000000; font: normal 20px arial, helvetica, sans-serif; border:dashed 1px #DDD; padding:30px;} 
</style> 
</head> 
<body> 
<br /> 
<table border='0' cellspacing='10' cellpadding='0' id='tab' align='center'> 
<tr> 
<td> 
<b>Data:</b>{$_POST['Datas']}<br /> 
<b>Módulo:</b>{$_POST['Modulo']}<br /> 
<b>Assunto/Script:</b>{$_POST['AssuntoScript']}<br /> 
<b>Descrição/Alteração:</b>{$_POST['DescricaoAlteracao']}<br /> 
<b>Script/Informação:</b>{$_POST['ScriptInformacao']}<br /> 
<b>Responsável:</b>{$_POST['Responsavel']}<br /> 
<b>Tipo:</b>{$_POST['Tipo']}<br /> 
<b>Origem:</b>{$_POST['Origem']}<br /> 
</td> 
</tr> 
</table> 
<br /> 
</body> 
</html> 
"; 



$html2 = "<!DOCTYPE html>
<html lang='pt'> 
<head> 
<meta charset='UTF-8'>
<style> 
body     {background:#FFFFFF;} 
a, a:link   {color:#5b6105; text-decoration:none;} 
#tab     {margin:0; padding:0px; width:500px; border:1px solid #8F8E96; padding:10px;} 
#tab tr {background:#065b17; } 
#tab td {color:#000000; font: normal 20px arial, helvetica, sans-serif; border:dashed 1px #DDD; padding:30px;} 
</style> 
</head> 
<body> 
<br /> 
<table border='0' cellspacing='10' cellpadding='0' id='tab' align='center'> 
<tr> 
<td> 
<b>Data:</b>{$_POST['Datas']}<br /> 
<b>Módulo:</b>{$_POST['Modulo']}<br /> 
<b>Assunto/Script:</b>{$_POST['AssuntoScript']}<br /> 
<b>Descrição/Alteração:</b>{$_POST['DescricaoAlteracao']}<br /> 
<b>Script/Informação:</b>{$_POST['ScriptInformacao']}<br /> 
<b>Responsável:</b>{$_POST['Responsavel']}<br /> 
<b>Tipo:</b>{$_POST['Tipo']}<br /> 
<b>Origem:</b>{$_POST['Origem']}<br /> 
</td> 
</tr> 
</table> 
<br /> 
</body> 
</html> 
"; 







//criar variável do Anexo
$arquivo = $_FILES['arquivo'];


//habilitar SMTP
$mail->isSMTP();

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

//debug para informar os erros
$mail->SMTPDebug=2; // 0-nada 1-msg cliente e servidor 3-tudo


//Host
$mail->Host = 'smtp.gmail.com';

//tipo de proteção
$mail->SMTPSecure = "tls";

//porta
$mail-> Port = 587;

//autenticação
$mail->SMTPAuth = true;

//detalhes da conta de email
$mail->Username='[email protected]';
$mail->Password='xxxxxx';

//detalhes do email
$mail->isHTML(true);
$mail->setFrom ('[email protected]', 'Site');
$mail->addAddress ('[email protected]');
$mail->Subject = 'Relatorio xxxxxx';
$mail->AddAttachment($arquivo['tmp_name'], $arquivo['name'] );
$mail->Body = $html;







//mensagem de envio ou erro
if ($mail->send())
    echo "email enviado com sucesso";
else echo "Deu ruim";

?>



</html>

1 answer

0

to whom it may interest, I managed to solve with switch, as follows:

in the archive gravar_enviar.php

//detalhes do email
$mail->isHTML(true);
$mail->setFrom ('[email protected]', 'Site');
$mail->addAddress ('[email protected]');
$mail->Subject = 'Relatorio xxxx';
$mail->AddAttachment($arquivo['tmp_name'], $arquivo['name'] );


switch ($ScriptInformacao) {
    case "Script":
        $mail->Body = $html1;
        break;
    case "Informação":
        $mail->Body = $html2;
        break;
    default:
        echo "Não selecionado";
}

Browser other questions tagged

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