小弟接触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('sagahl@126.com', 'live', 'huling@xxxxx.com', 'work', 'askjdkas', $config,'test.html'); }
?
?以上的代码完成了通过模板发送邮件。修改邮件的样式只需要修改邮件的模板。
由于是刚刚接触php,不知道php中是不是已经实现了以上功能的代码?或者是否有更好的解决方案?希望能抛砖引玉。