linux/window配置php PEAR:Mail發(fā)送html郵件,,有需要的朋友可以參考下,。
介紹一下linux和windows下配置PEAR:Mail,,用來發(fā)送html郵件,做記錄備份,。
大體上配置分為以下幾步:
- 安裝pear(高版本的php里已經(jīng)自帶安裝pear)
- pear安裝Mail,,Mail_Mime,Net_SMTP
- Yii框架組件代碼測試
(一)安裝pear
(1)Windows系統(tǒng)
本人php安裝路徑D:\local\PHPnow\php-5.2.14-Win32,,版本5.2.14.
D:\local\PHPnow\php-5.2.14-Win32查看路徑下是否有pear.bat,,如果沒有說明未安裝,參考一下步驟,。
- 下載go-pear,,http://pear.php.net/go-pear,并重命名為go-pear.php,,放到D:\local\PHPnow\php-5.2.14-Win32目錄下,;
- 打開cmd,cd到D:\local\PHPnow\php-5.2.14-Win32,,運行php.exe go-pear.php,,根據(jù)提示,一路回車直到安裝完成,;
- 雙擊生成的D:\local\PHPnow\php-5.2.14-Win32目錄下的PEAR_ENV.reg,,導(dǎo)入相關(guān)信息到注冊表;
- 修改php.ini,,include_path,,如下:
; UNIX: "/path1:/path2"
;include_path = ".:/php/includes"
;
; Windows: "\path1;\path2"
include_path = ".;D:\local\PHPnow\php-5.2.14-Win32\PEAR" - 重啟apache
(2)linux系統(tǒng)
本人測試Red Hat Enterprise Linux Server release 5.4 (Tikanga),,php安裝路徑/usr/local/php,版本5.2.17
首先驗證/usr/local/php/bin目錄下是否有pear文件,,如果有,,則說明已經(jīng)安裝。php高版本已經(jīng)可以自帶安裝pear,,php5.2.17便自帶安裝,。
如果未安裝,請參考:
【以下轉(zhuǎn)載自】http://blog./uid-25266990-id-3393387.html
在搭建centreon的過程中,,需要pear模塊支持,。
什么是pear
pear是PHP擴展與應(yīng)用庫(the PHP Extension and Application Repository)的縮寫。它是一個PHP擴展及應(yīng)用的一個代碼倉庫,,簡單地說,,
pear就是PHP的cpan。
在官網(wǎng)上有說明詳細(xì)的安裝信息,,這里作簡單說明,。
http://pear.php.net/manual/en/about-pear.php
我的PHP目錄為/usr/local/php5
在Linux下安裝PHP的PEAR:
1)下載
#curl -o go-pear.php http://pear.php.net/go-pear
如果提示:
PHP Warning: PHP Startup: Invalid library (maybe not a PHP library) ‘json.so’ in Unknown on line 0
Sorry! Your PHP version is too new (5.2.9) for this go-pear.
Instead use http://pear.php.net/go-pear.phar for a more stable and current
version of go-pear, more suited to your PHP version.
那么要從http://pear.php.net/go-pear.phar獲取。
#curl -o go-pear.php http://pear.php.net/go-pear.phar
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 3594k 100 3594k 0 0 186k 0 0:00:19 0:00:19 –:–:– 196k
會在當(dāng)前目錄下載go-pear.php 頁面,。
2)運行g(shù)o-pear.php
# /usr/local/php5/bin/php go-pear.php
3)這里按回車?yán)^續(xù)安裝,,CTRL+C放棄安裝。
Below is a suggested file layout for your new PEAR installation. To
change individual locations, type the number in front of the
directory. Type ‘a(chǎn)ll’ to change all of them or simply press Enter to
accept these locations.
1. Installation base ($prefix) : /usr/local/php5
2. Temporary directory for processing : /tmp/pear/install
3. Temporary directory for downloads : /tmp/pear/install
4. Binaries directory : /usr/local/php5/bin
5. PHP code directory ($php_dir) : /usr/local/php5/lib/php
6. Documentation directory : /usr/local/php5/docs
7. Data directory : /usr/local/php5/data
8. User-modifiable configuration files directory : /usr/local/php5/cfg
9. Public Web Files directory : /usr/local/php5/www
10. Tests directory : /usr/local/php5/tests
11. Name of configuration file : /usr/local/php5/etc/pear.conf
1-11, ‘a(chǎn)ll’ or Enter to continue:
Beginning install…
Configuration written to /usr/local/php5/etc/pear.conf…
Initialized registry…
Preparing to install…
installing phar://go-pear.phar/PEAR/go-pear-tarballs/Archive_Tar-1.3.7.tar…
installing phar://go-pear.phar/PEAR/go-pear-tarballs/Console_Getopt-1.3.0.tar…
installing phar://go-pear.phar/PEAR/go-pear-tarballs/PEAR-1.9.4.tar…
installing phar://go-pear.phar/PEAR/go-pear-tarballs/Structures_Graph-1.0.4.tar…
installing phar://go-pear.phar/PEAR/go-pear-tarballs/XML_Util-1.2.1.tar…
install ok: channel://pear.php.net/Archive_Tar-1.3.7
install ok: channel://pear.php.net/Console_Getopt-1.3.0
install ok: channel://pear.php.net/Structures_Graph-1.0.4
install ok: channel://pear.php.net/XML_Util-1.2.1
install ok: channel://pear.php.net/PEAR-1.9.4
PEAR: Optional feature webinstaller available (PEAR’s web-based installer)
PEAR: Optional feature gtkinstaller available (PEAR’s PHP-GTK-based installer)
PEAR: Optional feature gtk2installer available (PEAR’s PHP-GTK2-based installer)
PEAR: To install optional features use “pear install pear/PEAR#featurename”
** WARNING! Old version found at /usr/local/php5/bin, please remove it or be sure to use the new /usr/local/php5/bin/pear command
The ‘pear’ command is now at your service at /usr/local/php5/bin/pear
** The ‘pear’ command is not currently in your PATH, so you need to
** use ‘/usr/local/php5/bin/pear’ until you have added
** ‘/usr/local/php5/bin’ to your PATH environment variable.
Run it without parameters to see the available actions, try ‘pear list’
to see what packages are installed, or ‘pear help’ for help.
For more information about PEAR, see:
http://pear.php.net/faq.php
http://pear.php.net/manual/
重啟apache,。
(二)pear安裝pear安裝Mail,,Mail_Mime,Net_SMTP
接著用pear安裝插件,,我們可以在http://pear.php.net/packages.php網(wǎng)站上查看pear可安裝的包,,為了發(fā)送html郵件,我們只需要安裝Mail,,Mail_Mime,,Net_SMTP(Networking)。安裝Net_SMTP的時候會自動安裝Net_Socket.
安裝過程比較簡單:
Windows:用cmd執(zhí)行
D:\local\PHPnow\php-5.2.14-Win32\pear.bat install Mail
D:\local\PHPnow\php-5.2.14-Win32\pear.bat install Mail_Mime D:\local\PHPnow\php-5.2.14-Win32\pear.bat install Net_SMTP
linux類似:
/usr/local/php/bin/pear install Mail
/usr/local/php/bin/pear install Mail_Mime
/usr/local/php/bin/pear install Net_SMTP
安裝完畢重啟apache,,接下來便是測試了,。
(三)Yii框架組件代碼測試
先可以參考官網(wǎng)示例:http://pear.php.net/manual/en/package.mail.mail-mime.example.php
<?php
include 'Mail.php';
include 'Mail/mime.php' ;
$text = 'Text version of email';
$html = '<html><body>HTML version of email</body></html>';
$file = '/home/richard/example.php';
$crlf = "\n";
$hdrs = array(
'From' => '[email protected]',
'Subject' => 'Test mime message'
);
$mime = new Mail_mime(array('eol' => $crlf));
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file, 'text/plain');
$body = $mime->get();
$hdrs = $mime->headers($hdrs);
$mail =& Mail::factory('mail');
$mail->send('postmaster@localhost', $hdrs, $body);
?>
如以上成功發(fā)送郵件,說明php pear mail安裝配置成功~
測試成功可發(fā)送郵件以后,,我們探討一下如何在Yii框架中配置通用郵件發(fā)送模塊,。
我們使用smarty模版引擎來生成html郵件中的htmlbody內(nèi)容,搭建Yii框架郵件發(fā)送的通用模塊,,關(guān)鍵在于郵箱賬戶輕松配置,、新郵件內(nèi)容的smarty模版頁面容易添加、郵件發(fā)送接口方便調(diào)用,。Smarty模版引擎的使用這里不再贅述,。
先看看要實現(xiàn)的效果:
<?php
class SiteController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout = "http://layouts/column2";
public function actionTest()
{
try {
$model = new FormModel();
$model->_test = 1; //此處為FormModel里變量,,用于渲染到smarty模版里
$mailSettings = array (
'resetPassword' => array(
'name'=>'wefuture',
'from'=>'[email protected]',
'to'=>'[email protected]',
'cc'=>"",
'vipcc'=>"",
'subject'=>'重置密碼',
'template'=>'resetPassword.htm',
'attachments'=>array(),
),
);
$model->sendMail($mailSettings, 'resetPassword', "[email protected]");
} catch(Exception $e) {
var_dump($e->getMessage());
}
}
} 如上,,發(fā)送一封郵件,,我們只需要關(guān)心好好的填寫郵件配置信息,寫好“resetPassword”模版引擎內(nèi)容渲染到郵件中即可,,怎么樣,,是不是很方便。
接著我們看看FormModel里函數(shù)做了些什么:
<?php
/**
* Controller is the customized base controller class.
* All controller classes for this application should extend from this base class.
*/
class FormModel extends CFormModel
{
public $_test;
public function init() {
}
/**
* auto trim all
*/
public function setAttributes($values, $safeOnly=true)
{
if (is_array($values)) {
foreach ($values as $name => $val) {
if (is_string($val)) {
$values[$name] = trim($val);
}
}
}
return parent::setAttributes($values,$safeOnly);
}
/**
* auto trim all
*/
public function beforeValidate()
{
if (is_array($this->attributes)) {
foreach ($this->attributes as $name => $val) {
if (is_string($val)) {
$this->$name = trim($val);
}
}
}
return parent::beforeValidate();
}
/**
* 發(fā)送郵件函數(shù)
*
*/
public function sendMail($mailSettings, $settingName, $TO = null, $CC = null ,$setPage=1) {
if(!isset($mailSettings[$settingName])){
echo "mail setting for $settingName not found!";
die();
}
$mailSetting = $mailSettings[$settingName];
$attachments = array();
if (isset($mailSetting['attachments']) && $setPage == 1) {
foreach($mailSetting['attachments'] as $key=>$value) {
$attachments[]=$value;
}
}
if($TO) { //如果指定收件人
$to = $TO;
} else {
$to = $mailSetting['to'];
}
if($CC) { //如果指定抄送人
$cc = $CC;
} else {
$cc = $mailSetting['cc'];
}
if(isset($this->isContainVip)
&& $this->isContainVip
&& isset($mailSetting['vipcc'])
&& strlen($mailSetting['vipcc']) > 0){
$vipcc = $mailSetting['vipcc'];
$cc = $cc . "," . $vipcc;
}
$subject = $mailSetting['subject'];
$from = $mailSetting['from'];
$name = $mailSetting['name'];
$html = true;
$data = array(
'model' => $this,
);
$ret = Yii::app()->messenger->sendSmartyMail($to, $cc, $subject, $mailSetting['template'], $data, $from, $name, $html, $attachments);
if ($ret == false) {
$this->addError('email', '發(fā)送郵件失敗');
return false;
} else {
Yii::log('發(fā)送郵件成功,, subject: ' . $subject, 'info');
}
return true;
}
}
代碼里用到,,Yii::app()->messenger->sendSmartyMail,我在工程里自己配置了組件messager,、smarty,,看看messager文件類內(nèi)容:
<?php
require_once('Mail.php');
require_once('Mail/mime.php');
/**
* class Messenger.
*
* 發(fā)送郵件
*
* 支持html格式和純文本格式;
* 支持使用應(yīng)用對應(yīng)的smarty模版生成郵件內(nèi)容,;
* 支持發(fā)送附件
*
* 所有的郵件內(nèi)容,,變量使用utf-8編碼
*/
class Messenger
{
public $mailer;
public $options;
public function init() {
if (empty($this->mailer)) {
$this->mailer = 'mail';
}
}
/**
* 發(fā)送使用smarty模板的郵件
*
* 使用系統(tǒng)配置的smarty模板路徑下的 mail/$template.html作為模板文件
*
* @param string $to 逗號分隔的收件人列表
* @param string $subject 郵件的主題
* @param string $template 模版名稱
* @param array $data 需要替換的模版變量數(shù)組($template_var => $template_value)
* @param string $from 發(fā)件人的email
* @param string $name 發(fā)件人的顯示名
* @param boolean $html 郵件是否是html格式,默認(rèn)為true
* @param array $attachments 附件文件路徑列表,,默認(rèn)為空
*/
public function sendSmartyMail($to, $cc, $subject, $template, $data, $from, $name, $html=true, $attachments=array()) {
if (!isset($to) || ($to == "")) {
return;
}
if (!isset($cc) || ($cc == "")) {
$cc = '';
}
// 可以配置將所有郵件都發(fā)到一個郵件地址或列表
// 用于測試時,,避免發(fā)出垃圾郵件騷擾大家
$sendAllMailTo = Yii::app()->params['DEBUG_SEND_ALL_MAIL_TO'];
if (!empty($sendAllMailTo)) {
$to = $sendAllMailTo;
$cc = $sendAllMailTo;
}
$smarty = Yii::app()->smarty;
$smarty->assign($data);
$content = $smarty->fetch('mail/'.$template);
$hdrs = array(
'Return-Path' => $from,
'From' => "$name <$from>",
'To' => $to,
'Subject' => "=?UTF-8?B?".base64_encode($subject)."?=",
'Date' => date("r"),
);
if($cc != ""){
$ccHeader = array('Cc' => $cc);
$hdrs = array_merge($hdrs, $ccHeader);
}
$param = array(
'text_charset' => 'utf-8',
'head_charset' => 'utf-8',
'html_charset' => 'utf-8',
);
$mime = new Mail_mime();
if ($html){
$mime->setHtmlBody($content);
}
else{
$mime->setTXTBody($content);
}
foreach ($attachments as $att) {
$mime->addAttachment($att);
}
$body = @$mime->get($param);
$hdrs = @$mime->headers($hdrs);
$email = &Mail::factory($this->mailer, $this->options);
/**
* 2011年3月的Net_SMTP有個bug,對timeout的處理有問題,,而PEAR的Mail_smtp類并沒有正確的初始化Net_SMTP
* 導(dǎo)致Net_SMTP對timeout的bug傳遞出來,。如果在smtp對象上調(diào)用connect方法后(getSMTPObject以后),
* 再調(diào)用setTimeout(新版Net_SMTP才有),則問題可以繞過,。
* 該問題只在PEAR Net_SMTP v1.5.0和v1.5.1上存在
* see https://pear.php.net/bugs/bug.php?id=18335&edit=12&patch=Net_SMTP-bug18335.diff&revision=latest
*/
$result = &$email->getSMTPObject();
if (PEAR::isError($result)) {
Yii::log('初始化SMTP對象失?。?.$result->getMessage(), 'error');
return $false;
}
// workaround Net_SMTP bug
if (method_exists($result, 'setTimeout')) {
$result->setTimeout(3600); // 1 hour
}
//只有放到recipients里,才會收到郵件,。至于顯示到To還是Cc由header決定,。
$recipients = isset($hdrs['Cc'])? $hdrs['To'].','.$hdrs['Cc']:$hdrs['To'];
$ret = $email->send($recipients, $hdrs, $body);
if (PEAR::isError($ret)) {
Yii::log('發(fā)送郵件錯誤:'.$ret->getMessage(), 'error');
return false;
} else {
Yii::log('發(fā)送郵件成功,Subject: ' . $subject, 'info');
}
return true;
}
/**
* 發(fā)送郵件
*
* @param string $to 逗號分隔的收件人列表
* @param string $subject 郵件的主題
* @param array $content 郵件內(nèi)容
* @param boolean $html 郵件是否是html格式,,默認(rèn)為否
* @param string $from 發(fā)件人的email
* @param string $name 發(fā)件人的顯示名
* @param array $attachments 附件文件路徑列表
*/
public function sendMail($to, $subject, $content, $html=false, $from="[email protected]", $name="wefuture", $attachments=array()) {
if (!isset($to) || ($to == "")) {
return;
}
// 可以配置將所有郵件都發(fā)到一個郵件地址或列表
// 用于測試時,,避免發(fā)出垃圾郵件騷擾大家
$sendAllMailTo = Yii::app()->params['DEBUG_SEND_ALL_MAIL_TO'];
if (!empty($sendAllMailTo)) {
$ori = $to;
$to = $sendAllMailTo;
$content = "原郵件接收人:".$ori."\n 現(xiàn)接收人:".$sendAllMailTo." \n 內(nèi)容是:\n ".$content;
}
$hdrs = array(
'Return-Path' => $from,
'From' => "$name <$from>",
'Subject' => $subject,
);
$param = array(
'text_charset' => 'UTF-8',
'head_charset' => 'UTF-8',
'html_charset' => 'UTF-8',
);
$mime = new Mail_mime();
if ($html) {
$mime->setHtmlBody($content);
}
else {
$mime->setTXTBody($content);
}
foreach ($attachments as $att) {
$mime->addAttachment($att);
}
$body = @$mime->get($param);
$hdrs = @$mime->headers($hdrs);
$email = &Mail::factory($this->mailer, $this->options);
$ret = $email->send($to, $hdrs, $body);
if (PEAR::isError($ret)) {
Yii::log('發(fā)送郵件錯誤:'.$ret->getMessage(), 'error');
return false;
}
return true;
}
}
上面一個類就挺簡單了,用到了smarty,、php pear mail模塊,。最后再貼出一下main.php的config配置加入一下代碼:
'smarty' => array(
'class'=>'lib.thirdparty.CSmarty',
'templatePath' => $WEB_BASE_DIR.'/smarty',
),
'messenger' => array(
'class' => 'lib.common.Messenger',
'mailer' => 'smtp',
'options' => array(
'auth' => true,
'host' => 'smtp.exmail.qq.com',
'username' => '[email protected]',
'password' => 'xxxxxxxxx',
),
),
至此,基于Yii框架利用php pear mail發(fā)送html郵件的配置工作就完成啦~
以上Yii框架適合對Yii框架經(jīng)驗較豐富者參考,,直接復(fù)制可能不行很好運行,,僅提供一種思路和核心代碼。
|