View php file on the body of an email

Asked

Viewed 53 times

-1

I’m using Phpmailer to send emails, I want to encapsulate the content of a php page in the field: $mail->Body, this page that should be included in the body does search in the mail tracking api and return the data in a processed manner. I tried file_get_contents but it didn’t work because the page to be inserted makes a request. I tried Curl but it does not give me the expected return, returns a string with the amount of characters or "Resource id#7".inserir a descrição da imagem aqui

<?php

    session_start();

    require "./biblioteca/PHPmailer/Exception.php";
    require "./biblioteca/PHPmailer/OAuth.php";
    require "./biblioteca/PHPmailer/PHPMailer.php";
    require "./biblioteca/PHPmailer/POP3.php";
    require "./biblioteca/PHPmailer/SMTP.php";

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


    class Mensagem {

        public $status = array('codigo_status' => null, 'descricao_status' => '');
    
        public function __get($atributo) {
            return $this->$atributo;
        }
        public function __set($atributo, $valor) {
            $this->$atributo = $valor;
        }
    }
    


    $mensagem = new Mensagem();

    $mail = new PHPMailer(true);


    $url = "http://localhost/e-lastic/e-lastic-brasil/template_email.php";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    $rastreio = curl_exec($ch);
    
    
    try {
        //Server settings
          ...
        // Attachments
                                     
        $mail->addAttachment('pdf.php', 'email.pdf');         // Add attachments
        //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

        // Content
        $mail->isHTML(true);                                  // Set email format to HTML
        $mail->Subject = "Sua encomenda chegou";
        $mail->Body    = 

        var_dump($rastreio);
    
        $mail->AltBody = 'Necessário usar um client que suporte HTML para ter acesso total ao conteúdo dessa mensagem';

        $mail->send();

        $mensagem->status['codigo_status'] = 1;
        $mensagem->status['descricao_status'] = 'Email enviado com sucesso!';

    } catch (Exception $e) {

        $mensagem->status['codigo_status'] = 2;
        $mensagem->status['descricao_status'] = 'Não foi possível enviar esse email! Detalhes do erro: ' . $mail->ErrorInfo;
    }
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="../assets/css/main.min.css">
    <link rel="stylesheet" href="../assets/css/bootstrap.css">
    <link rel="stylesheet" href="../assets/css/mdb.min.css">

</head>

<body>


    <div class="modal fade" id="exemplomodal" tabindex="-1" role="dialog" aria- labelledby="myLargeModalLabel">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-body">

                    <div class="row">
                        <div class="col-md-12">

                            <? if ($mensagem->status['codigo_status'] == 1) { ?>

                            <div class="container">
                                <div class="row">
                                    <div class="col-6">
                                        <h1 class="display-4 text-success">
                                            Sucesso
                                        </h1>
                                    </div>
                                    <div class="col-6">

                                    </div>
                                </div>

                                <p>
                                    <?= $mensagem->status['descricao_status'] ?>
                                </p>


                                <a href="http://gabrielquintino.scprojetista.com/"
                                    class="btn btn-success btn-lg mt-5 text-white">Voltar
                                </a>

                            </div>

                            <? } ?>

                            <? if ($mensagem->status['codigo_status'] == 2) { ?>

                            <div class="container">
                                <h1 class="display-4 text-danger">
                                    Ops!
                                </h1>
                                <p>
                                    <?= $mensagem->status['descricao_status'] ?>
                                </p>

                                <div class="modal-footer">
                                    <a href="http://gabrielquintino.scprojetista.com/"
                                        class="btn btn-danger btn-lg mt-5 text-white">Voltar
                                    </a>
                                </div>

                            </div>
                            <? } ?>

                        </div>
                    </div>

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

    <!-- END MODAL -->

    <!-- end pedir meu chip -->
    <script src="./js/jquery.js"></script>
    <script src="./js/bootstrap.min.js"></script>
    <script src="./js/all.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $('#exemplomodal').modal('show');
    })
    </script>
</body>

</html>

  • The var_dump was just to check the data output? Ever tried without it?

  • This, just to display the result, already tried with printf tbm but it does not work, with echo is not allowed.

  • Try to use ob_start() and ob_get_clean()

  • You won’t be able to put the php code inside the body and wait for it to run at some point, you have to render the result, get the generated html and put in the body.

2 answers

0

After trying hard, I was able to render the contents on the

<?$mail->Body    = 
    
    '<a class="navbar-brand" href="https://elastic.fit/">
        <img src="http://e-lastic.scprojetista.com/logo-color-small.png" width="150" height="30" alt="logo" />
    </a><hr /><br />'.'
    <h3 style="color: #0c80a3">
        <img src="http://e-lastic.scprojetista.com/icone.jpg" width="20" height="20" alt="ícone" />'.    
        $titulo.'
    </h3>'.'
    <p>Você pode acompanhar o envio com o códio de rastreamento
        <a href="https://www2.correios.com.br/sistemas/rastreamento/default.cfm">'.
        $_SESSION['obj'].
        '</a><br />
    </p>';
    if ($rastreio[0]['action'] === "Objeto entregue ao destinatário") {
        $mail->Body   .= 
            '<img src="http://e-lastic.scprojetista.com/entregue.jpg" width="400" height="40" alt="">';
        }
    elseif($rastreio[0]['action'] === "Objeto em trânsito - por favor aguarde"){
        $mail->Body   .= 
            '<img src="http://e-lastic.scprojetista.com/encaminhando.png" width="400" height="40" alt="logo" />';
        }
    else {
        $mail->Body   .= '<img src="http://e-lastic.scprojetista.com/horario_limite.jpg" width="400" height="40" alt="logo" />';
        }

    foreach($rastreio as $key=> $obj){
    
    $mail->Body   .= 

    '<hr />
    <table>
        <tr>
            <td>';
            if ($obj['date'] !== 'O') {
                $mail->Body   .= 
                $obj['date']."<br />". $obj['hour']."<br />". $obj['location'];
            }
            $mail->Body   .= 
            '</td>
             <td>';
             if ($obj['date'] !== 'O') {
                $mail->Body   .= 
                $obj['message'];
             }
             $mail->Body   .= 
            '</td>
        </tr>
    </table>';
    
}

?>

0

you can try it the way below, I believe it is the best way without using frameworks.

ob_start();


/**
** Minha classe pra enviar email usando phpmailer
** 
**/
$alerta = new ControllerEmail();

$alerta->addAtachImage(getRoot("/assets/img/logos/logo-email.png"), "logo");

/**
** Variável assunto é requerida no arquivo view.email.contrato-analize.php
** @var @assunto
**/
$assunto = "Assunto teste";

require viewsPathEmail("view.email.contrato-analize.php");

/**
** Essa variável $resultsHTML você pode por em $mail->Body = $resultsHTML;
**
*/
$resultsHTML = ob_get_clean();

Browser other questions tagged

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