【问题标题】:Send email with a template using php使用 php 发送带有模板的电子邮件
【发布时间】:2011-04-12 00:49:28
【问题描述】:

如何使用 php 发送电子邮件,然后在电子邮件中添加模板设计?我正在使用这个:

$to = "someone@example.com";  
$subject = "Test mail";  
$message = "Hello! This is a simple email message.";  
$from = "someonelse@example.com";  
$headers = "From: $from";  
mail($to,$subject,$message,$headers);  
echo "Mail Sent.";  

而且效果很好!问题只是如何添加模板。

【问题讨论】:

    标签: php templates email


    【解决方案1】:

    为什么不尝试这样简单的事情:

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

    您的模板文件类似于:

    <html>
    
    <p>My name is {{ name }} and I am {{ age }} !</p>
    
    </html>
    

    【讨论】:

    • 这正是我想要的!
    • 我更喜欢您的解决方案。很简单。
    • 辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!辉煌!太棒了!....
    • 顺便说一句,这是Mustache的基础。安装后,使用就像$m = new Mustache_Engine; echo $m-&gt;render("template.html", $variables); 一样简单
    • 如果是数组呢?
    【解决方案2】:

    让我们对此有一个小小的突破:)

    class Emailer
    {
        var $recipients = array();
        var $EmailTemplate;
        var $EmailContents;
    
        public function __construct($to = false)
        {
            if($to !== false)
            {
                if(is_array($to))
                {
                    foreach($to as $_to){ $this->recipients[$_to] = $_to; }
                }else
                {
                    $this->recipients[$to] = $to; //1 Recip
                }
            }
        }
    
        function SetTemplate(EmailTemplate $EmailTemplate)
        {
            $this->EmailTemplate = $EmailTemplate;            
        }
    
        function send() 
        {
            $this->EmailTemplate->compile();
            //your email send code.
        }
    }
    

    注意函数SetTemplate() ...

    这是一个小模板类

    class EmailTemplate
    {
        var $variables = array();
        var $path_to_file= array();
        function __construct($path_to_file)
        {
             if(!file_exists($path_to_file))
             {
                 trigger_error('Template File not found!',E_USER_ERROR);
                 return;
             }
             $this->path_to_file = $path_to_file;
        }
    
        public function __set($key,$val)
        {
            $this->variables[$key] = $val;
        }
    
    
        public function compile()
        {
            ob_start();
    
            extract($this->variables);
            include $this->path_to_file;
    
    
            $content = ob_get_contents();
            ob_end_clean();
    
            return $content;
        }
    }
    

    这是一个小例子,您仍然需要完成脚本的核心,但这将为您提供一个不错的布局以开始使用。

    $emails = array(
        'bob@bobsite.com',
        'you@yoursite.com'
    );
    
    $Emailer = new Emailer($emails);
     //More code here
    
    $Template = new EmailTemplate('path/to/my/email/template');
        $Template->Firstname = 'Robert';
        $Template->Lastname = 'Pitt';
        $Template->LoginUrl= 'http://stackoverflow.com/questions/3706855/send-email-with-a-template-using-php';
        //...
    
    $Emailer->SetTemplate($Template); //Email runs the compile
    $Emailer->send();
    

    这就是它的全部内容,只需要知道如何使用对象,从那里开始就很简单了,哦,模板看起来有点像这样:

    Welcome to my site,
    
    Dear <?php echo $Firstname ?>, You have been registered on our site.
    
    Please visit <a href="<?php echo $LoginUrl ?>">This Link</a> to view your upvotes
    
    Regards.
    

    【讨论】:

    • 干得好。 compile方法中的extract语句不需要在include语句之前吗?
    • 不需要在加载之前调用它,这允许定义模板变量并在模板内容的范围内。
    • 嗨罗伯特,伟大的 sn-p 但我不确定我是否遵循邮件的发送方式。您可以轻松地将模板编译成 SetTemplate,但是没有发送功能,并且 Emailer 类没有扩展任何 Mailer 类(带有发送或 mail() 功能)......我在这里遗漏了什么吗?
    • @RobertPitt 缺少分号 ;) $this->variables[$key] = $val
    【解决方案3】:

    我的简单例子

    模板.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;
      }
    }
    ?>
    

    联系我们.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>"; 
    }
    ?>
    

    【讨论】:

      【解决方案4】:
              $message_to_client = file_get_contents("client_email.html");
              //$message_to_client = "bla bla {{ EMAIL }} bla bla";
      
      
              $variables = array(
                  'SITE_TITLE' => $SITE_TITLE,
                  'SITE_LOGO' => $SITE_LOGO,
                  'SITE_URL' => $SITE_URL,
                  'CLIENT_NAME' => strip_tags($data->clientname),
                  'PHONE' => strip_tags($data->phone),
                  'EMAIL' => strip_tags($data->email),
                  'CITY' => strip_tags($data->city),
                  'REGION' => strip_tags($data->region),
                  'COMMENT' => htmlentities($data->comment)                
              );
      
              $message_to_client = preg_replace_callback('/{{([a-zA-Z0-9\_\-]*?)}}/i',
                   function($match) use ($variables) { 
                       return  $variables[$match[1]]; 
              }, $message_to_client );
      

      【讨论】:

        【解决方案5】:

        创建您的模板文件,例如,

        /path/to/templates/template.twig:

        亲爱的{{name}},

        感谢您就 {{subject}} 给我们写信。

        然后按照https://twig.symfony.com/doc/2.x/api.html 的说明安装和使用带有Composer 的twig 模板引擎

        require_once '/path/to/vendor/autoload.php';
        
        $loader = new Twig_Loader_Filesystem('/path/to/templates');
        $twig = new Twig_Environment($loader, array());
        

        然后呈现并发送您的电子邮件:

        $to = "someone@example.com";  
        $subject = "Test mail";  
        $message = $twig->render('template.twig', array(
           'name' => 'Fred',
           'subject' => 'philately',
        ));
        $from = "someonelse@example.com";  
        $headers = "From: $from";  
        mail($to,$subject,$message,$headers);  
        

        【讨论】:

          【解决方案6】:

          是的,您可以使用电子邮件模板发送电子邮件,例如

          $to_email = 'xyz@xzy.com';
          
          // Set content-type header for sending HTML email 
          $headers = "MIME-Version: 1.0" . "\r\n"; 
          $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 
          
          ob_start();
              require __DIR__.'/email_template.php';
          $htmlContent = ob_get_clean();
           
          $subject = 'Test Emails';
          // Send email 
          if( mail( $to_email , $subject, $htmlContent, $headers ) ) {
               echo 'send';
          } else { 
          echo 'error'; } 
          

          这样做的好处是,您还可以在电子邮件模板文件中直接使用变量时传递变量。

          【讨论】:

            【解决方案7】:

            您可以像在调用文件中一样在模板中使用$this

            您只需要在ob_start 命令之后包含模板并检索其内容:

            $this->customer = 1234;    //* This variable is used in the template
            ob_start();
            include 'template.php';
            $template = ob_get_clean();
            var_dump($template);      //* Outputs '<b>1234</b>'
            
            // template.php
            <b><? echo $this->customer ?></b>
            

            【讨论】:

              【解决方案8】:

              首先,你必须制作一个 HTML 模板:

              <form action="#" id="ContactForm" method="post" enctype="multipart/form-data">
                  <table border="0" cellspacing="5" cellpadding="5" style="background-color:#CCCCCC; text-align:center;">
                      <tr>
                           <td width="15%">Name:</td>
                           <td width="85%"><input name="name" type="text" required></td>
                       </tr>
                       <tr>
                           <td>Email:</td>
                           <td><input name="email" type="email" required></td>
                       </tr>
              
                       <tr>
                           <td colspan="2"><input name="sub" type="submit" value="Submit"></td>
                       </tr>
              
                   </table>                      
              </form>
              

              下面的代码是使用模板的邮件代码。

              if ($_SERVER["REQUEST_METHOD"] == "POST") {
                  $name=$_REQUEST['name'];
                  $email=$_REQUEST['email'];
                  $to=$email; //change to ur mail address
                  $subject="UandBlog - Send Email Template Demo";
                  $message =  file_get_contents('Your template path'); // Your Template        
                  $headers = 'MIME-Version: 1.0'."\r\n";
                  $headers .= 'Content-type: text/html; charset=iso-8859-1'."\r\n";
                  $headers .= "From: noreply@uandblog.com"; 
              
                  mail($to, $subject, $message, $headers); 
              }
              

              您也可以从UandAblog下载带有模板的完整代码。

              【讨论】:

                【解决方案9】:

                如果你使用的是 phpmailer,那么试试这个

                // Content
                $mail->isHTML(true); 
                $mail->Subject = 'Newsletter Mail';
                $mail->Body = file_get_contents('mail.html');
                if (!$mail->send()) {
                    echo 'Mailer Error: ' . $mail->ErrorInfo;
                }
                

                如果你使用的是 php 邮件,那么只需要添加

                $body= file_get_contents('mail.html');
                $headers = 'MIME-Version: 1.0'."\r\n";
                $header.="Content-Type: text/html;\n\tcharset=\"iso-8859-1\"\n";
                $header .="From:<no-reply@youremail.com>\r\n";
                

                如果你使用 CI(Codeigniter) 那么 就我而言,我创建了 ci 的邮件助手,但其余工作相同

                $message = $this->load->view('front/invoice_email',$data, TRUE); //"Hi, 9999999999 \r\n".";
                if(!empty($adminEmail)) {
                  send_user_mail($adminEmail, $message, $subject);
                }
                

                【讨论】:

                  【解决方案10】:

                  试试这个

                  <?php
                  $to = "somebody@example.com, somebodyelse@example.com";
                  $subject = "HTML email";
                  
                  $message = "
                  <html>
                  <head>
                  <title>HTML email</title>
                  </head>
                  <body>
                  <p>This email contains HTML Tags!</p>
                  <table>
                  <tr>
                  <th>Firstname</th>
                  <th>Lastname</th>
                  </tr>
                  <tr>
                  <td>John</td>
                  <td>Doe</td>
                  </tr>
                  </table>
                  </body>
                  </html>
                  ";
                  
                  // Always set content-type when sending HTML email
                  $headers = "MIME-Version: 1.0" . "\r\n";
                  $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                  
                  // More headers
                  $headers .= 'From: <webmaster@example.com>' . "\r\n";
                  $headers .= 'Cc: myboss@example.com' . "\r\n";
                  
                  mail($to,$subject,$message,$headers);
                  ?>
                  

                  【讨论】:

                    【解决方案11】:

                    试试这个……

                    $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); 
                    

                    【讨论】:

                      猜你喜欢
                      • 2015-11-11
                      • 1970-01-01
                      • 2013-06-22
                      • 2016-07-12
                      • 1970-01-01
                      • 2016-01-30
                      • 1970-01-01
                      • 2018-07-11
                      • 2020-09-08
                      相关资源
                      最近更新 更多