PHP筆記:利用Php Mailer及Postfix,透過網頁發送郵件

在開發網站系統的時侯,我們往往會遇到需要讓系統發送郵件給用戶的狀況(例如發送系統通知信)。但到底要怎樣做,才能夠達到這個效果呢?
方法其實很簡單--在網頁裡引入PHP Mailer,這個開源的PHP函数包即可。

但在沒有SMTP伺服器的情況下,即使有了PHP Mailer,我們仍然沒有辦法透過它發送郵件給用戶。這種時侯,我們有兩個選擇:
1,將Gmail等免費的郵件服務作為SMTP伺服器;2,自己在伺服器上架設SMTP伺服器。

前者在網絡上已經有許多教學,因此本文的重點將會集中在如何利用Postfix和PHP mailer這對組合來發送郵件。

註:以下的示範以Ubuntu12.04為準。

首先,我們需要安裝Postfix,以及Mailx這兩個軟體在伺服器上:
sudo apt-get install postfix
sudo apt-get install mailutils

在安裝Postfix的時侯,程式會要求你設定郵件伺服器的環境,這個時侯請選擇「Internet Site」,並輸入你的郵件伺服器域名(例如mail.example.com)

以上步驟皆完成後,我們便可以透過以下指令測試郵件伺服器是否安裝成功:
telnet localhost 25
ehlo localhost
mail from: root@localhost
rcpt to: (任何你想寄信的郵件地址)
data
Subject: Test
It is a test mail for postfix
.
quit

之後檢查郵箱,確認郵件是否順利寄出。假如收到郵件,即代表Postfix已經安裝成功了。

在確認郵件伺服器可以正常運作後,在伺服器上新增一個寄信專用的帳號:
sudo useradd -m -s /bin/bash webmaster
這樣接著寄信的時侯我們都可以透過這個帳號來發送郵件,而不必使用Root。

在Postfix安裝好後,接下來便是Php Mailer的部份:

首先,我們需要先下載 PhpMailer的檔案,並將其解壓縮。
在解壓縮出來的檔案中,我們會用到的只有_acp-ml/modules下的phpmailer這個部份,其他檔案暫時派不上用場。

找到phpmailer這個檔案夾後,將其上傳至/var/www(即是你的Apache伺服器檔案夾),並修改權限:
sudo chmod 755 /var/www/phpmailer
sudo chmod 755 /var/www/phpmailer/class.smtp.php
sudo chmod 755 /var/www/phpmailer/class.phpmailer.php

假如你的網頁伺服器和郵件伺服器並非同一個伺服器,則需要修改一下class.phpmailer.php的內容:

vi /var/www/phpmailer/class.phpmailer.php


如圖,將$Host的部份修改成你的郵件伺服器域名即可。

但在這個情況下,PhpMailer將無法透過郵件伺服器發送郵件,而伺服器亦可能無法分析域名。因此,我們還得重新設定一下Postfix和系統才行:
vi /etc/postfix/main.cf
在mynetwork的127.0.0.0/8 後加上你的伺服器IP地址,這樣Postfix才會接受phpmailer的請求。

接著,修改/etc下的host檔案:
127.0.0.1 localhost
127.0.1.1 ubuntu
在這兩行下面輸入你的伺服器IP以及域名(例如192.168.0.1 mail.example.com)

這麼一來,便可以使用Phpmailer的功能來發送郵件了。

以下是透過Phpmailer來發送郵件的程式碼範例:

<html>
<head>
<title>Example</title>
</head>
<?php
require(./phpmailer/class.phpmailer.php);
mb_internal_encoding(UTF-8);
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = false;
$mail->FromName = Root;
$webmaster_email = root@mail.example.com;
$email=example@gmail.com;
$name=Example;
$mail->From = $webmaster_email;
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,Squall.f);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = Test;
//Html環境下,郵件的內容(可以使用Html Tag)
$mail->Body = It is the testing mail;
//純文字環境下,郵件的內容
$mail->AltBody = It is the testing mail;
if(!$mail->Send()){
echo Sent Failed
}
else{
echo Sent Successed;
}
?>

 

參考資料:

http://wiki.ubuntu.com.cn/Postfix_%E5%9F%BA%E6%9C%AC%E8%AE%BE%E7%BD%AE%E6%8C%87%E5%8D%97
http://belleaya.pixnet.net/blog/post/27410978-%5B%E6%95%99%E5%AD%B8%5D-php-%E5%88%A9%E7%94%A8-phpmailer-%E9%80%8F%E9%81%8E-gmail-%E5%AF%84%E4%BF%A1

發佈留言