鍍金池/ 問答/PHP  HTML/ phpmailer 的 $mail->Body 是否可以收納到一個文件中?

phpmailer 的 $mail->Body 是否可以收納到一個文件中?

$mail->Body = '';

我發(fā)現我要寄信時,我會寫入一整個 html + css 語法,還會添加 php 語言
就像是:

$mail->Body = '
    <html>
    <head>
    '.$phpmailerCssStyle.'
    </head>

    <body>
    <div class="edm-layout">
      <img src="'.$host_url.'images/logo.png">
      <div class="line"></div>
    </div>

    <div class="edm-content">
      <div class="edm-hithere">
        嗨,'.$getUser['name'].' <br>XXX '.$prodTotal.' XXXXX<br>XXXXXX'.formatProductPrice($thisTotal).' XXX
      </div>';

        $row_distinct = mysqli_fetch_array($cako_id_distinct);

        $cako_data = $pdo->query(
          "SELECT XXXXXXX "
        );
        $mail->Body .= '
        <div class="edm-products">
          '.$row_distinct['XXXX'];
          
          //.......
          
          </body>
    </html>

類似那麼長的代碼
我是否可以把它收納到一個文件中,只要簡單引入就可以了?

$mail->Body = 'xxx.php'; or require_once...

有辦法實現嗎?
或其他方式?
至少我在這一頁的代碼不會看到這一長串的代碼.....

回答
編輯回答
神曲

上文中所寫的代碼極其危險

建議對于這種嵌有HTML的內容 通過使用模板文件進行存儲,使用占位符的形式來對內容進行替換。

建議方案

  • email.template
<html>
    <head>
        {$phpmailer_css_style}
    </head>

    <body>
    <div class="edm-layout">
      <img src="{$host_url}images/logo.png">
      <div class="line"></div>
    </div>

    <div class="edm-content">
      <div class="edm-hithere">
        嗨,{$user_name} <br>XXX {$prod_total}XXXXX<br>XXXXXX{$this_total} XXX
      </div>
      
        <div class="edm-products">
            {$row_distinct}
        </div>
      </div>
    </div>
  </body>
</html>
  • EmailTemplate.php

<?php
$php_version = version_compare(phpversion(), '7');
/**
 * 必須php 7
 */
if ($php_version === -1) {
    die('Need a high version of php 7.1.*');
}
/**
 * EmailTemplate
 */
class EmailTemplate
{
    /**
     * @param string $template_path 模板路徑
     * @param array $args 變量組
     * @return string 渲染后的
     * @throws Exception
     */
    public static function render(string $template_path, array $args): string
    {
        if (!file_exists($template_path)) {
            throw new Exception("Not found template fiel.", 1);

        }
        $template = file_get_contents($template_path);
        $result = preg_replace_callback('!\{\$(\w+)\}!', function ($matches) use ($args) {
            $arg = $matches[1];
            return $args[$arg] ?? '';
        }, $template);
        return $result;
    }
}
  • demo.php
$body = EmailTemplate::render(
    'email.template',
    [
        'host_url' => 'http://xxx',
        'phpmailer_css_style' => 'empty',
        'user_name' => '張三',
        'prod_total' => '100.00',
        'this_total' => '10000.00',
        'row_distinct' => 'empty',
    ]
);

這樣就實現了一個簡單的模板替換。

2018年7月23日 20:43
編輯回答
清夢

舉個簡單的例子吧。

demo.php

<?php
$getUser = [
    'name' => '張三'
];
$prodTotal = '999';

$body = require('email.php');

echo $body;

email.php

<?php
return '嗨,'.$getUser['name'].' <br>XXX '.$prodTotal.' XXXXX<br>XXXXXX';

運行 demo.php,輸出:

嗨,張三 
XXX 999 XXXXX
XXXXXX
2017年7月28日 14:02
編輯回答
哎呦喂

謝邀,確實可以寫的很簡單,但不是這樣寫:
$mail->Body = 'xxx.php'; or require_once...
你可以這樣寫

$body = get_file_contents('xxx.html');
$body = str_replace('{{head}}',$head,$body);
$body = str_replace('{{contant}}',$contant,$contant);
$mail->Body = $body;
2017年1月23日 16:34
編輯回答
巫婆
  • 答案:可以
  • 解決方案:Smarty框架的fetch方法
  • 案例(就是來自文檔):

    • 該方法簡單使用:

      
      <?php
      include('Smarty.class.php');
      $smarty = new Smarty;
      
      $smarty->setCaching(true);
      
      // 按照URL來MD5生成一個特定的緩存ID
      $cache_id = md5($_SERVER['REQUEST_URI']);
      
      // 捕獲輸出
      $output = $smarty->fetch('index.tpl', $cache_id);
      
      // 處理輸出的內容
      echo $output;
      ?>
      
          
    • 模板:

      // 這是模板
      Dear {$contact_info.name},
      
      Welcome and thank you for signing up as a member of our user group.
      
      Click on the link below to login with your user name
      of '{$contact_info.username}' so you can post in our forums.
      
      {$login_url}
      
      List master
      
      {textformat wrap=40}
      This is some long-winded disclaimer text that would automatically get wrapped
      at 40 characters. This helps make the text easier to read in mail programs that
      do not wrap sentences for you.
      {/textformat}
      
      
    • 發(fā)送郵件:

      
      <?php
      
      // 從數據庫或其他來源獲取到$contact_info
      
      $smarty->assign('contact_info',$contact_info);
      $smarty->assign('login_url',"http://{$_SERVER['SERVER_NAME']}/login");
      
      mail($contact_info['email'], 'Thank You', $smarty->fetch('email_body.tpl'));
      
      ?>
      
  • 原理及其說明:

    • 框架中的模板引擎本質就是將模板解析到成目標字符串,然后交由HTTP返回客戶端
    • 而模板引擎和框架本身是獨立存在的,所以模板引擎肯定會有一個方法,作用是:(resultText)=F(template),在Smarty中就是fetch方法
    • 理論上,模板引擎都可以實現你的需求
    • 而且,使用模板引擎比起自己來拼接,不管是維護性、安全性、魯棒性都更好
2018年8月27日 14:53