PHP 下發送 Email

文章位置: 主頁 > 文章資料庫 > PHP 教學 > PHP 下發送 Email
瀏覽次數: 24088
更新時間: 2005/05/30 19:56

本文將會講述 PHP 下發送 Email 的功能。一般上要在 PHP 下發送電郵,會使用內建的 mail() 函式,除非有特定需要才會使用 socket 發送電郵的方法。今天會先從 mail() 函式入門。

php.ini 設定

要讓 web server 可以發送 email,先要打開 php.ini 修改 sendmail_path 及 SMTP,如果是用 web hosting 的服務則不用理會這點。

如果使用的是 unix like 環境,一般會在 sendmail_path 設定:如果在 win32 環境,便需在 SMTP 裡面填上可以作 rely 的 email server。

設定好 php.ini 後需要 restart web server。

mail() 基本語法

要在 PHP 下發信十分簡單,只要使用內建的 mail() 函式即可。而需要發送一封 email,最少需要 "收件者電郵地址", "郵件主旨" 及 "郵件內容" 三項資料,以下例子是發送一封郵件到 testing@testing.com,主旨是 "testing email",內容是 "This is a testing!":

01 <?php
02 mail
("testing@testing.com""testing email""This is a testing!");
03
?>


P.S. 如果需要在 email 內換行,可使用 "\n" 字元。

當使用以下方法發送 email 成功後,可能你會看到一個大問題,就是收件者收取 email 後,會寄件者及寄件者電郵那裡會使用 web server 預設的資料,要改進這點,便需要在使用 mail() 函式時加入第四個參數 -- header。以是語法與以上相同,不是之處是會設定 email 寄件者及寄件者 email:

01 <?php
02 mail
("testing@testing.com""testing email""This is a testing!""From:My Name<me@mydomain.com>");
03
?>


以上例子會使用 My Name 作為寄件者名稱,而 me@mydomain.com 會是寄件件者電郵。

發送 HTML 郵件

以上所介紹的方法會發送純文字的郵件,對於一般應用也可應付,當需要作加入圖片或定義字體大小就不可以了,但直接在郵件內容打上 html 又會直接給收件者顯示 html 標記語言,而不是預期的效果。


其實使用 mail() 函式發送 HTML 郵件,關鍵在 header 參數。請看以下例子,大致內容與上面的例子一樣:

01 <?php
02
// this is the email content
03
$email_content '<html><head><title>testing</title><body bgcolor="#FFFFFF" text="#000000"><b>This is a <i>html</i> email.</b></body></html>';
04
05
mail("testing@testing.com""testing email"$email_content"From:My Name<me@mydomain.com>\nContent-Type:text/html");
06
?>


你可以看到,以上例子的郵件內容使用了 html 標記語言,而在 header 參數那裡加入了 "Content-Type:text/html"。


以上對 mail() 函式作了一個簡單的介紹,如對本文有任何意見或指正,在可本站討論區內提出,謝謝!


====================================================
歡迎轉載,但轉載時請保留此宣告,不得作為商業用途
作者: Sam Tang <admin{at}phpini{dot}com>
來源網站: http://www.phpdc.com/


用戶評論 按這裡發表新評論 
edward edward at hk82 dat com
17 June 2005 01:18
如何是attachment 又如何?
 
? user at yourdomain dat com
26 January 2012 23:45
hey
 
pkvdrmlyng gwhjtz at gmltux dat com
16 November 2011 20:31
6MyqQO , [url=http://xksxxizelgem.com/]xksxxizelgem[/url], [link=http://tgfbpiypjmqt.com/]tgfbpiypjmqt[/link], http://nagfapktqbvw.com/
 
pfplhh pplgli at hnpons dat com
16 November 2011 03:02
T5xl9j <a href="http://nqftjsrzlonq.com/">nqftjsrzlonq</a>
 
Kassi info at cybesex3d dat de
15 November 2011 23:28
I have been so bewildeerd in the past but now it all makes sense!
 
tgtyyt user at yourdomain dat com
11 October 2011 15:12
yyyy
 
 
 發表評論
姓名:
Email:
內容: