Address of the namespace

Asked

Viewed 88 times

0

I have the file below that sends authenticated emails normally:

<?php            

        ini_set("display_errors",true);
        ini_set("display_startup_erros",1);

        error_reporting(E_ALL && E_NOTICE);
    error_reporting( E_ALL | E_STRICT ); // PHP 5.3
    error_reporting( E_ALL ); // Todas as outras versões 

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    use PHPMailer\PHPMailer\SMTP;

    require_once 'PHPMailer/PHPMailer.php';
    require_once 'PHPMailer/Exception.php';
    require_once 'PHPMailer/SMTP.php';

    require_once '_global/_erros/erros.ini';
    require_once '_controles/_util/Constantes.php';

    $constantes = new Constantes();

    $caixaPostalServidorNome=$constantes->getTituloSite();
    $caixaPostalServidorEmail= $constantes->getEmailSite();
    $caixaPostalServidorSenha=$constantes->getSenhaEmailSite();

    $email = "[email protected]";   
    $nome = "Carlos";
    $assunto =  "Testando...."; 
    $mensagem = "Indo bem";

    $mail = new PHPMailer(true);
     //Server settings
    $mail->SMTPDebug = 2;               
    $mail->isSMTP();                   
    $mail->Host = 'smtp.'.$constantes->getDominioSite();
    $mail->SMTPAuth = true;   
    $mail->Username  = $caixaPostalServidorEmail;
    $mail->Password  = $caixaPostalServidorSenha;
    $mail->SMTPSecure = 'TLS';               
    $mail->Port = 587;                                 

    //Recipients      
    $mail->From  = $caixaPostalServidorEmail;
    $mail->FromName  = utf8_decode($caixaPostalServidorNome); 
    $mail->Subject  = utf8_decode($assunto);
    $mail->Body  = utf8_decode($mensagem);


    $mail->AddAddress($email,utf8_decode($nome));

    if ($mail->send()) {

        $_SESSION["success"] = "Mensagem enviada com sucesso";

    } else {

        $_SESSION["danger"] = "Erro ao enviar mensagem " . $mail->ErrorInfo;

    }
?>

So I thought I’d put in the $mail in a class and call it from a file and stayed like this: In time: This was necessary because the above code was done from an example and without the proper validations, etc...

<?php                

        ini_set("display_errors",true);
        ini_set("display_startup_erros",1);
        error_reporting(E_ALL && E_NOTICE);
    error_reporting( E_ALL | E_STRICT ); // PHP 5.3
    error_reporting( E_ALL ); // Todas as outras versões 

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    use PHPMailer\PHPMailer\SMTP;   

    require_once "PHPMailer/PHPMailer.php";     
    require_once "PHPMailer/Exception.php";     
    require_once "PHPMailer/SMTP.php";

    require_once "_controles/_conexao/Conexao.php";
        require_once "_controles/_util/Constantes.php";
    require_once "_controles/_util/PhpUtil.php";    
    require_once "_controles/_models/Emails.php";
    require_once "_controles/_daos/EmailsDao.php";
    require_once "_controles/_models/EmailEnviar.php";
    require_once "_controles/_daos/EmailEnviarDao.php";

    $connection = new Conexao(); 
    $conexao = $connection->abreConexao();
        $constantes = new Constantes();  
        $phpUtil = new PhpUtil();   

    $_POST["nome"] = "Carlos";
    $_POST["email"] = "[email protected]";
    $_POST["telefone"] = "";
    $_POST["assunto"] = 2;
    $_POST["descricao"] = "Tentei né?";

        $assunto = $phpUtil->retornaContatoTipos($_POST["assunto"]);    
    $emailsDao = new EmailsDao($conexao);

    $qual = isset($_POST["qual"]) ? $_POST["qual"] : "";

    $_POST["telefone"] = preg_replace( '#[^0-9]#', '', $_POST["telefone"] );


    if (
          strlen($_POST["telefone"]) > 0 && 
          strlen($_POST["telefone"]) != 10 && 
          strlen($_POST["telefone"]) != 11) {

        echo "ERRO";

    } else {

        $email = new Emails(
                         date("Y-m-d"), 
                     "n", 
                     $_POST["nome"], 
                     $_POST["email"], 
                     $_POST["telefone"],
                     $_POST["assunto"], 
                     $_POST["descricao"]);

        $email->setQual($qual);


        $emailsDao->cadastrar($email);
        // Apenas para popular o texto abaixo
        $assunto = $_POST["assunto"] == 4 ? $_POST["qual"] : $phpUtil->retornaContatoTipos($_POST["assunto"]);  

        $texto  = "<h2>".$constantes->getTituloSite()."</h2><br />";
        $texto .= "<img style='display:block; margin:0 auto;' src='".$constantes->getHttpSite()."/_img/logo.png' />";
        $texto .= "<b>Olá, você nos enviou um e-mail com a seguinte mensagem:</b><br /><br />";
        $texto .= "<b>Nome:</b> ".$_POST["nome"]."<br /><br />";
        $texto .= "<b>Telefone:</b> ".$phpUtil->formataTel($_POST["telefone"])."<br /><br />";
        $texto .= "<b>E-mail:</b> ".$_POST["email"]."<br /><br />";
        $texto .= "<b>Interesse:</b> ".$assunto."<br /><br />";
        $texto .= "<b>Descrição:</b><br />".nl2br($_POST["descricao"])."<br /><br /><br />";
        $texto .= "Estaremos respondendo o mais rápido possível<br /><br />";

        $emailEnviar = new EmailEnviar( 
              $_POST["nome"], 
              $_POST["email"],
              $constantes->getTituloSite(), 
              "contato@".$constantes->getDominioSite(), 
              "Re: ".$assunto,
              $texto
        );




        $emailEnviarDao = new EmailEnviarDao();

        $enviarEmail = $emailEnviarDao->enviaEmail($emailEnviar, $constantes);

        echo $enviarEmail["success"] == 1 ? "OK" : "ERRO";

    }

?>

Until the line below everything goes well:

$enviarEmail = $emailEnviarDao->enviaEmail($emailEnviar, $constantes);

But when you enter the class I created for sending:

<?php            

  class EmailEnviarDao {

    public function __construct() {}

    public function enviaEmail($email, $constantes)  {

       $caixaPostalServidorNome=$constantes->getTituloSite();
       $caixaPostalServidorEmail= $constantes->getEmailSite();
       $caixaPostalServidorSenha= $constantes->getSenhaEmailSite();
       $host = 'smtp.'.$constantes->getDominioSite();

       $enviaFormularioParaNome = $email->getNomeAlvo();
       $enviaFormularioParaEmail = $email->getEmailAlvo();    
       $assunto =  $email->getAssunto();      
       $mensagem = $email->getDescricao();

       $mail = new PHPMailer(true);

       //Server settings
       $mail->SMTPDebug = 2;               
       $mail->isSMTP();                    
       $mail->Host = $host;
       $mail->SMTPAuth = true;   
       $mail->Username  = $caixaPostalServidorEmail;
       $mail->Password  = $caixaPostalServidorSenha;
       $mail->SMTPSecure = 'TLS';               
       $mail->Port = 587;                                 

        //Recipients      
       $mail->From  = $caixaPostalServidorEmail;
       $mail->FromName  = utf8_decode($caixaPostalServidorNome); 
       $mail->Subject  = utf8_decode($assunto);
       $mail->Body  = utf8_decode($mensagem);

       $mail->AddAddress($enviaFormularioParaEmail,utf8_decode($enviaFormularioParaNome));

       if($mail->Send()){

            return array("success"=>1,"errors"=>"0K");

       } else {

            return array("success"=>0,"errors"=>$mail->ErrorInfo);

       } 

    }   

  }

?>

Then I get an error but cannot debug.

That is the error:

Fatal error: Uncaught Error: Class 'PHPMailer' not found in C:\Program Files\Apache24\Apache24\htdocs\funerariasaopedro.net.br\_controles\_daos\EmailEnviarDao.php:19 Stack trace: #0 C:\Program Files\Apache24\Apache24\htdocs\funerariasaopedro.net.br\enviar.php(93): EmailEnviarDao->enviaEmail(Object(EmailEnviar), Object(Constantes)) #1 {main} thrown in C:\Program Files\Apache24\Apache24\htdocs\funerariasaopedro.net.br\_controles\_daos\EmailEnviarDao.php on line 19

It seems like class addressing error inside the other but I’m not getting it right and understanding.

  • Are you using Composer or some autoload?

  • Composer. But as I said, if the aqryuivo caller with the Composer is at the root fdunciona. The problem is the .. / at the beginning

  • If you use Composer autoload, all require are unnecessary. Simply import the class/namespace into the scope that Composer takes care of the rest. As for these ../ namespace does not exist. namespace is always absolute.

  • So in fact the only thing I know. (I am untaught in Poser) is that if the names are all in one folder, that is, the Phpmailler folder and the calling file, then it works. Otherwise, it gives this error]

  • added more details to the question

1 answer

1


Good afternoon, in your file Emailenviardao.php on line 19 you are instantiating the object of Phpmailer as well to do this before you need:

  1. Include class, with require, include or etc.
  2. Use the namespace (use PHPMailer\PHPMailer\PHPMailer etc) or else when instantiating inform the full path of the NS.

Since you are not doing this in this file, it arrives on line 19 and the interpreter does not have the definition of the Phpmailer class and with this generates the fatal error.


Tip, use a better IDE because the IDE itself on line 19 should/should be telling you that the class is not available.

Browser other questions tagged

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