Use PHP variables in PHPMailer HTML email body [duplicate]

this question already has answers here : Send email with dynamic content in PHP (3 responses) Closed for 4 years.

Staff need to send the following message by email using phpMailer: "Hello, [name]! There is a new protocol concerning document Nº [xxx]".

I managed to set everything right, however the location intended for the name and number remain blank. I managed to rescue both and put in variables, plus their values are not loaded in the message. Here is an excerpt from the code:

<tr>
    <p> Olá, <?php echo $nome ?>! </p>
</tr>
<tr>
    <p>
        Há um novo protocolo referente ao documento nº <?php echo $controle ?>.
    </p>
</tr>

The variable $nome saves the name of the user who will receive the email and controle control the document control number.


This is the class that contains the send function using phpMailer:

 class emailDAO {

    function avisoProcesso($nome, $email, $controle){

        $mensagem = "
                <table width='800' hidden='300' xmlns=\"http://www.w3.org/1999/html\"     border='no'>
                    <tr>
                        <img src='http://goo.gl/evcwLn'>
                    </tr>
                    <tr bgcolor='#E0E6F8' height='150'>
                        <p>
                            <b>
                                <h1>                                      
                                    Olá, <?php echo $nome ?>!
                                </h1>
                            </b>
                        </p>
                        <p>                              
                            Há um novo protocolo referente ao documento nº <?php echo $controle ?>.
                        </p>
                    </tr>                        
                </table>";

    $mail = new PHPMailer(); //
    // Define o método de envio
    $mail->Mailer = "smtp";
    // Define que a mensagem poderá ter formatação HTML
    $mail->IsHTML(true);
    // Define que a codificação do conteúdo da mensagem será utf-8
    $mail->CharSet    = "utf-8";
    // Define que os emails enviadas utilizarão SMTP Seguro tls
    $mail->SMTPSecure = "tls";
    // Define que o Host que enviará a mensagem é o Gmail
    $mail->Host       = "smtp.gmail.com";
    //Define a porta utilizada pelo Gmail para o envio autenticado
    $mail->Port       = "587";
    // Deine que a mensagem utiliza método de envio autenticado
    $mail->SMTPAuth   = "true";
    // Define o usuário do gmail autenticado responsável pelo envio
    $mail->Username   = "[email protected]";
    // Define a senha deste usuário citado acima
    $mail->Password   = "senha";
    // Defina o email e o nome que aparecerá como remetente no cabeçalho
    $mail->From       = "[email protected]";
    $mail->FromName   = "Notificação";
    // Define o destinatário que receberá a mensagem
    $mail->AddAddress($email);
    //Define o email que receberá resposta desta mensagem, quando o destinatário responder.
    $mail->AddReplyTo("[email protected]", $mail->FromName);
    // Assunto da mensagem
    $mail->Subject    = "DTEC - Nova Solicitação";

    // Toda a estrutura HTML e corpo da mensagem do e-mail.
    $mail->Body       = $mensagem;

    // Controle de erro ou sucesso no envio
    if (!$mail->Send()){?>
        <script>
            alert("Houve um erro no envio do e-mail de cadastro, caso deseje pode fazer manualmente.");
        </script>
    <?php }else{ ?>
        <script>
            alert("Um e-mail foi enviado avisando sobre a criação deste protocolo.");
        </script>
    <?php }
}

Everything works perfectly, except for a blank space where I want the user name and the document control number to appear.

The function is called at the end of the registration sending the three parameters( nome name ,email email and controle control); I did the check and the three variables receive the content correctly. However it does not display in the body of e-amyl.

Author: Maniero, 2016-02-11

2 answers

You can also simplify this process by using str_replace().

Instead of opening and closing php tags in your html you can create a macro and make the substitution.

Example:

$body = '<tr>
    <p> Olá, [NOME]! </p>
</tr>
<tr>
    <p>
        Há um novo protocolo referente ao documento nº [CONTROLE].
    </p>
</tr>';

// Dados
$nome = 'Gabriel Rodrigues';
$controle = 'Dados do Controle';
// Substituindo Macros pelos valores.
$body = str_replace('[NOME]', $nome, $body);
$body = str_replace('[CONTROLE]', $controle, $body);
echo $body;

Makes it a lot easier if you need to replace more than one field with the same value.

 2
Author: Gabriel Rodrigues, 2016-02-11 15:01:06

You can use ob_start() for this

ob_start();
// seu codigo php aqui
$mensagem = ob_get_contents();
ob_end_clean();

$mail = new PHPMaier(); //  
$mail->Mailer = "smtp";
$mail->IsHTML(true);
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = "[email protected]";
$mail->Password = "senha";
$mail->From = "[email protected]";
$mail->FromName = "Notificação";
$mail->AddAddress($email);
$mail->AddReplyTo("[email protected]", $mail->FromName);
$mail->Subject = "DTEC - Nova Solicitação";
$mail->Body = $mensagem;

if (!$mail->Send()){ ?>
....

Http://php.net/manual/en/function.ob-start.php

 0
Author: pho3nix, 2016-06-15 12:06:43