PHP使用範本管理員郵件樣式
小弟接觸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)); }?
?測試的模板
| please input your inf |
| name:{$user} |
| password:{$password} |
?
?測試代碼
$config = array ( 'user' => 'huling', 'password' => '123456' ); $mail = new SendMailTool('smtp.xxxx.com', 'huling', 'aqsdsadsad'); $mail->sendVMMail([email protected]', 'live', [email protected]', 'work', 'askjdkas', $config,'test.html'); }?
?以上的程式碼完成了通過模板發送郵件。修改郵件的樣式只需要修改郵件的模板。
由於是剛剛接觸php,不知道php中是不是已經實現了以上功能的代碼?或者是否有更好的解決方案?希望能拋磚引玉。