欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PHP使用模板管理邮件样式 PHP项目管理Zend框架HTML 

程序员文章站 2022-07-14 17:57:27
...

小弟接触php第3日,公司要做个发邮件的模块。项目中使用的php框架是zend framework。但是在网上看到的例子中,要想发html样式邮件,html代码必须全部包含在字符串里。这样修改起来不好预览邮件的版式。如果要是能直接写个邮件模板,发的时候调用该模板,系统渲染模板得到最终的邮件。于是尝试自己动手写该功能。

首先编写发送邮件功能

class SendMailTool extends Zend_Mail_Transport_Smtp {

    protected $mail;

    protected $transport;

    public function __construct($smtpserver = 'smtp.hgsamerica.com', $username, $password) {

        $config = array (
            'auth' => 'login',
            'username' => $username,
            'password' => $password
        );
        $this->transport = new Zend_Mail_Transport_Smtp($smtpserver, $config);

    }

    /**
     * 用于基本的发送邮件
     */
    public function sendMail($to, $toname, $from, $fromname, $title, $contant) {
        $this->mail = new Zend_Mail("UTF-8");
        $this->mail->setDefaultTransport($this->transport);
        $this->mail->addTo($to, $toname);

        $this->mail->setBodyHtml($contant);
        $this->mail->setFrom($from, $fromname);

        $this->mail->setSubject("=?UTF-8?B?" . base64_encode($title) . "?=");
        $this->mail->send();
    }
//读取模板,替换模板中的变量
    private function loadVM($vmname, $config = Array ()) {

        $contant = '';
        $file = fopen("mailtemplates/" . $vmname, "r");
        while (!feof($file)) {
            $line = fgets($file);
            while (strpos($line, "{\$") > 0) {
                $counts = strpos($line, "{\$");
                $counte = strpos($line, "}");
                $substr = substr($line, $counts +2, $counte - $counts -2);
                $line = str_replace("{\$" . $substr . "}", $config[$substr], $line);
            }
            $contant .= $line;
        }
        return $contant;

    }

    /**
     * 发送模板邮件
     */
    public function sendVMMail($to, $toname, $from, $fromname, $title, $config, $vm) {
        $this->sendMail($to, $toname, $from, $fromname, $title, $this->loadVM($vm, $config));
    }
 



 测试的模板

<table>
    <tr>
        <td>
            please input your inf
        </td>
    </tr>
    <tr>
        <td>
            name:{$user}
        </td>
    </tr>
    <tr>
        <td>
            password:{$password}
        </td>
    </tr>
</table>
 



 测试代码

        $config = array (
            'user' => 'huling',
            'password' => '123456'
        );
        $mail = new SendMailTool('smtp.xxxx.com', 'huling', 'aqsdsadsad');

        $mail->sendVMMail('sagahl@126.com', 'live', 'huling@xxxxx.com', 'work', 'askjdkas',   $config,'test.html');
    }
 



 以上的代码完成了通过模板发送邮件。修改邮件的样式只需要修改邮件的模板。

由于是刚刚接触php,不知道php中是不是已经实现了以上功能的代码?或者是否有更好的解决方案?希望能抛砖引玉。