Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Mailer with HTML template and sending variables

Tags:

php

phpmailer

Basically I'm trying to do this.

http://www.xeweb.net/2009/12/31/sending-emails-the-right-way-using-phpmailer-and-email-templates/

Here is my code

index.php

    <?php 
    include('class.phpmailer.php'); // Retrieve the email template required 
    $message = file_get_contents('mail_templates/sample_mail.html'); 
    $message = str_replace('%testusername%', $username, $message); 
    $message = str_replace('%testpassword%', $password, $message); 
    $mail = new PHPMailer(); $mail->IsSMTP(); // This is the SMTP mail server 

    $mail->SMTPSecure = 'tls';
    $mail->Host = "smtp.gmail.com";
    $mail->Port = 587; 
    $mail->SMTPAuth = true; 
    $mail->Username = '[email protected]'; 
    $mail->Password = 'mypassword'; 
    $mail->SetFrom('[email protected]', 'Pricol Technologies'); 
    $mail->AddAddress('[email protected]'); 
    $mail->Subject = 'Your account information';
    $mail->MsgHTML($message);
    $mail->IsHTML(true); 
    $mail->CharSet="utf-8";
    //$mail->AltBody(strip_tags($message)); 
    if(!$mail->Send()) {  
    echo "Mailer Error: " . $mail->ErrorInfo;
    } 
    ?>

mail_templates/sample_mail.html

    <html>
    <body>
    <h1>Account Details</h1>
    <p>Thank you for registering on our site, your account details are as follows:<br>
    Username: %username%<br>
    Password: %password% </p>
    </body>
    </html> 

I'm getting the mail as follows:

    Account Details

    Thank you for registering on our site, your account details are as follows:
    Username: %testusername%
    Password: %testpassword%    

Expected Output

        Account Details

        Thank you for registering on our site, your account details are as follows:
        Username: testusername
        Password: testpassword

Where did I went wrong. I have checked some forum. But no use.

I have previously asked some question. But my project requirement is to have the html template with % variable name % so that anyone could make changes in the html file without touching the code part.

like image 555
user3350885 Avatar asked Jul 21 '14 15:07

user3350885


1 Answers

Two of these things are not like the others...

$message = str_replace('%testusername%', $username, $message); 
$message = str_replace('%testpassword%', $password, $message); 
                         ^^^^---note "test"


<p>Thank you for registering on our site, your account details are as follows:<br>
Username: %username%<br>
Password: %password% </p>
           ^---note the LACK of "test"

Your script is working perfectly as is, and it's a PEBKAC issue...

like image 182
Marc B Avatar answered Oct 25 '22 12:10

Marc B