PHP邮件发送器与HTML模板及发送变量

25

基本上我正在尝试做这件事。

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

这是我的代码:

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 = 'mygmailid@gmail.com'; 
    $mail->Password = 'mypassword'; 
    $mail->SetFrom('fromgmail@gmail.com', 'Pricol Technologies'); 
    $mail->AddAddress('addaddress@gmail.com'); 
    $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;
    } 
    ?>

邮件模板/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> 

我收到的邮件如下:

    Account Details

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

预期输出

        Account Details

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

我错在哪里了?我查看了一些论坛,但毫无用处。

我以前问过一些问题。但是我的项目要求使用带有%变量名称%的HTML模板,这样任何人都可以在不触及代码部分的情况下更改HTML文件。


2
在你的sample_mail.html文件中,在用户名和密码之前加上test。你只是忘记了test这一部分! - Jordan
优秀。帮了很多忙。 - user3350885
1
感谢您用代码这么好地提出了这个问题。虽然您的变量名有一个拼写错误,但是我从您的问题中得到了答案(模板中的%fieldname%),因为我不知道如何将注册表单中的表单字段传输到电子邮件发送程序中。 - Mario
1个回答

26

其中两个与其他不同...

$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"

你的脚本目前没有问题,而且这只是一个PEBKAC问题...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接