Send email with a template using php

后端 未结 9 2158
南旧
南旧 2020-12-04 07:45

How can I send an email using php then add a template design in the email? I\'m using this:

$to = \"someone@example.com\";  
$subject = \"Test mail\";  
$mes         


        
相关标签:
9条回答
  • 2020-12-04 08:23

    My simple example

    template.php

    <?php
    class Template
    {
      function get_contents($templateName, $variables) {
        $template = file_get_contents($templateName);
    
        foreach($variables as $key => $value)
        {
            $template = str_replace('{{ '.$key.' }}', $value, $template);
        }
        return $template;
      }
    }
    ?>
    

    contact-us.tpl

    Name: {{ name }}
    Email:  {{ email }}
    subject:  {{ subject }}
    ------messages------
    {{ messages }}
    ---------------------
    

    main.php

    <?php
    include_once 'template.php';
    
    $name = "Your name";
    $to = "someone@example.com";  
    $subject = "Test mail";  
    $message = "Hello! This is a simple email message.";  
    $from = "someonelse@example.com";  
    $headers = "From: $from"; 
    
    $text = Template::get_contents("contact-us.tpl", array('name' => $name, 'email' => $from, 'subject' => $subject, 'messages' => $message));
    echo '<pre>';
    echo $text;
    echo '<pre>';
    
    $mail = @mail($to, $subject, $text, $headers); 
    if($mail) {
      echo "<p>Mail Sent.</p>"; 
    }
    else {
      echo "<p>Mail Fault.</p>"; 
    }
    ?>
    
    0 讨论(0)
  • 2020-12-04 08:25

    Try this....

    $body='<table width="90%" border="0">
            <tr>
            <td><b>Name:</b></td> <td>'.$name.'</td>
            </tr>
            <tr>
            <td><b>Email:</b></td> <td>'.$email.'</td>
            </tr>
            <tr>
            <td><b>Message:</b></td> <td>'.$message.'</td>
            </tr>
            <tr></table>';
    
        mail($to,$subject,$body,$headers); 
    
    0 讨论(0)
  • 2020-12-04 08:28

    Why not try something as simple as this :

    $variables = array();
    
    $variables['name'] = "Robert";
    $variables['age'] = "30";
    
    $template = file_get_contents("template.html");
    
    foreach($variables as $key => $value)
    {
        $template = str_replace('{{ '.$key.' }}', $value, $template);
    }
    
    echo $template;
    

    Your template file being something like :

    <html>
    
    <p>My name is {{ name }} and I am {{ age }} !</p>
    
    </html>
    
    0 讨论(0)
提交回复
热议问题