Ir para conteúdo
Fórum Script Brasil
  • 0

PHPmailer(ok)+anexo(ok)+template(fail)


m3io

Pergunta

boas pessoal, faz um tempinho k já não vinha aqui.

agora consegui finalmente enviar email sem ser spam e ainda mais enviar um anexo,

mas agora queria tentar enviar com um template dinamico a receber as variaveis da mensagem e titulo etc...

vou postar aqui pra terem uma ideia

<html>
<head>
<title>PHP enviar email com anexo by m3io</title>
</head>
<body>

<?php
extract($_POST);     ///estrai o $_POST e converte o nome do post em variavel como, $_POST["nome"] = $nome

$template = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Email test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <p> </p>
    <center>
  <table width="80%" border="1">
      <tr>
        <th colspan="3" bgcolor="#CCCCCC" scope="col"><img src="http://cybercentro-braganca.pt/templates/mx_joofree2/images/logo.png" width="150" height="120" align="left"><h1>Email de: {%from_name%}</h1></th>
      </tr>
      <tr>
        <th width="6%" height="369" bgcolor="#CCCCCC" scope="row"> </th>
        <td width="89%" bgcolor="#999999">{%message%}</td>
        <td width="5%" bgcolor="#CCCCCC"> </td>
      </tr>
      <tr>
        <th colspan="3" bgcolor="#CCCCCC" scope="row">by m3io</th>
      </tr>
  </table>
  </center>
  </body>
</html>
';

  $template = str_replace('{%from_name%}', $from_name, $template);
  $template = str_replace('{%message%}', $body, $template);
em cima é basicamente onde esta um simples layout com uma tabela e cores, no email ele mostra isso tudo direitinho, mas não substitui os valores com o str_replace....
/* This is a sample callback function for PHPMailer Lite.
 * This callback function will echo the results of PHPMailer processing.
 */

/* Callback (action) function
 *   bool    $result        result of the send action
 *   string  $to            email address of the recipient
 *   string  $cc            cc email addresses
 *   string  $bcc           bcc email addresses
 *   string  $subject       the subject
 *   string  $body          the email body
 * @return boolean
 */

  
function callbackAction ($result, $to, $cc, $bcc, $subject, $body) {
  /*
  this callback example echos the results to the screen - implement to
  post to databases, build CSV log files, etc., with minor changes
  */
  $to  = cleanEmails($to,'to');
  $cc  = cleanEmails($cc[0],'cc');
  $bcc = cleanEmails($bcc[0],'cc');
  echo $result . "\tTo: "  . $to['Name'] . "\n\tTo: "  . $to['Email'] . "\n\tCc: "  . $cc['Name'] . "\n\tCc: "  . $cc['Email'] . "\n\tBcc: "  . $bcc['Name'] . "\n\tBcc: "  . $bcc['Email'] . "\n\n\t"  . $subject . "<br />\n";
  return true;
}

$testLite = false;

if ($testLite) {
  require_once '../class.phpmailer-lite.php';
  $mail = new PHPMailerLite();
} else {
  require_once '../class.phpmailer.php';
  $mail = new PHPMailer();
}

try {
  $mail->IsMail(); // telling the class to use SMTP
  $mail->SetFrom($_POST['from_address'], $_POST['from_name']);
  $mail->AddAddress($_POST['to_address'], $_POST['to_name']);
  $mail->Subject = $_POST['subject'];
  $mail->AltBody = 'Para visualizar a mensagem, por favor, use um visualizador de HTML e-mail compativel!'; // optional - MsgHTML will create an alternate automatically

    
  //$mail = file_get_contents('contents.html');   ////////ESTE AQUI ERA O ANTIGO
  
  $mail->MsgHTML($template);                    //////////////////////////////AQUI ELE CHAMA O TEMPLATE já COM OS VALORES SUBSTITUIDOS

  $mail->AddAttachment('test.png');      // attachment
//  $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
  $mail->action_function = 'callbackAction';
  
  $mail->Send();
  echo "Mensagem Enviada OK</p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}

function cleanEmails($str,$type) {
  if ($type == 'cc') {
    $addy['Email'] = $str[0];
    $addy['Name']  = $str[1];
    return $addy;
  }
  if (!strstr($str, ' <')) {
    $addy['Name']  = '';
    $addy['Email'] = $addy;
    return $addy;
  }
  $addyArr = explode(' <', $str);
  if (substr($addyArr[1],-1) == '>') {
    $addyArr[1] = substr($addyArr[1],0,-1);
  }
  $addy['Name']  = $addyArr[0];
  $addy['Email'] = $addyArr[1];
  $addy['Email'] = str_replace('@', '@', $addy['Email']);
  return $addy;
}

?>
</body>
</html>

o mais estranho de tudo é que testei so o template e a substituicao dos valores noutro ficheiro e funcionou, mas quando meto ele nessa class de email da erro.. :huh:

alguém pode dar alguma dica util????

valeu

Link para o comentário
Compartilhar em outros sites

3 respostass a esta questão

Posts Recomendados

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...