php也可以利用gmail發信 phpmailer

在php中有內建的mail函式不過這個方式要先在php.ini中進行設定而且功能非常有限,如果伺服器不是我們自己管的還真的不知道要怎麼辦!不過好險有phpmailer這個東西的推出
phpmailer 官網
這個套件可以幫助我們做更進階的發信功能,雖然他有提供php4,php5~6的版本不過,php4的我不想說了我們直接跳到php5的吧!
附帶一提:到目前為止(2011/3/22)官網上的下載連結是錯的~點php5版本的下載聯結還是走到php4版本的下載頁面
請點選下面連結下載正確的清單吧:
phpmailer 各版本下載


雖然應該要寫個教學範例,但是解壓縮以後竟然有一個examples資料夾耶!!挖~~最厲害的是他裡面的範例檔竟然還有專門為了gmail的伺服器寫的
也就是說拿著這個東西就可以利用gmail的伺服器發信給別人,真是佛心來的!!!


不過我們還是來小說明一下吧!
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "yourusername@gmail.com"; // GMAIL username
$mail->Password = "yourpassword"; // GMAIL password
$mail->AddReplyTo('name@yourdomain.com', 'First Last');
$mail->AddAddress('whoto@otherdomain.com', 'John Doe');
$mail->SetFrom('name@yourdomain.com', 'First Last');
$mail->AddReplyTo('name@yourdomain.com', 'First Last');
$mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML(file_get_contents('contents.html'));
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();

果然很簡單吧功能還很強大!就算沒有辦法控制伺服器還是可以發信摟



後記:
基本上要利用這個功能達到發信的動作是可以的,不過如果你要發送大批的電子報的話還是要先研究一下每個收信伺服器的擋信規則,才能讓訂戶可以收到信。不然通通都進垃圾信箱或是根本被當作黑名單就糗了

附帶一提,如果使用gmail的話要記得要先確定php.ini中有沒有打開openssl這個東東,如果沒有打開gmail會拒絕連線喔!

留言