2010年2月10日 星期三

如何在php程式中,用Gmail的mail server 發信(php 5.2.12)

在PHP程式中,利用程式自動發信的作法,可以採用phpMailer這個免費的class。在我的使用環境中,php的版本是win32 5.2.12

phpMailer 官方網站
http://phpmailer.codeworxtech.com/

下載 phpMailer
http://phpmailer.codeworxtech.com/index.php?pg=sf&p=dl

依據您使用的 PHP 版本之不同,來下載適合的class。
下載完畢後請解壓縮到指定資料夾中(我把它放在function的資料夾內),


function phpMail($subject,$body,$to){
require_once("function/class.phpmailer.php");
require_once("function/class.smtp.php");

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true; //設定SMTP需要驗證
$mail->SMTPSecure = "ssl"; // Gmail的SMTP主機需要使用SSL連線
$mail->Host = "smtp.gmail.com"; //Gamil的SMTP主機
$mail->Port = 465; //Gamil的SMTP主機的SMTP埠位為465埠。

$mail->Username = "xxxxxx"; //設定驗證帳號
$mail->Password = "xxxxxx"; //設定驗證密碼
$mail->From = "12345@gmail.com"; //設定寄件者信箱
$mail->FromName = "test"; //設定寄件者姓名

//設定收件者
$mail->AddAddress(33333@abc.com);
//設定密件副本
//$mail->AddBCC("55555@abc.com");

//設定信件字元編碼
$mail->CharSet="utf-8";
//設定信件編碼,大部分郵件工具都支援此編碼方式
$mail->Encoding = "base64";
//設置郵件格式為HTML
$mail->IsHTML(true);
//每50自斷行
$mail->WordWrap = 50;

//傳送附檔
//$mail->AddAttachment("upload/temp/filename.zip");
//傳送附檔的另一種格式,可替附檔重新命名
//$mail->AddAttachment("upload/temp/filename.zip", "newname.zip");

//郵件主題
$mail->Subject="abc";
//郵件內容
$mail->Body = "def";

//附加內容
// $mail->AltBody = '這是附加的信件內容';

//寄送郵件
if(!$mail->Send())
return "郵件無法順利寄出! Mailer Error: ".$mail->ErrorInfo;
}

要注意PHP必須支援SSL,才可用gmail寄信。在win32的php系統中,只要在安裝php的時候,將OpenSSL的dll安裝進來即可。若安裝時未安裝此一dll,再重新執行一次php安裝程式,在repair,remove,change中,選擇change的項目,再把OpenSSL加進來即可。
20100125000.jpg

  © Blogger templates Psi by Ourblogtemplates.com 2008

Back to TOP