本文將會講述 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!”:
1 2 3 |
<?php mail("testing@testing.com", "testing email", "This is a testing!"); ?> |
P.S. 如果需要在 email 內換行,可使用 “\n” 字元。
當使用以下方法發送 email 成功後,可能你會看到一個大問題,就是收件者收取 email 後,會寄件者及寄件者電郵那裡會使用 web server 預設的資料,要改進這點,便需要在使用 mail() 函式時加入第四個參數 — header。以是語法與以上相同,不是之處是會設定 email 寄件者及寄件者 email:
1 2 3 |
<?php mail("testing@testing.com", "testing email", "This is a testing!", "From:My Name<me@mydomain.com>"); ?> |
以上例子會使用 My Name 作為寄件者名稱,而 me@mydomain.com 會是寄件件者電郵。
發送 HTML 郵件
以上所介紹的方法會發送純文字的郵件,對於一般應用也可應付,當需要作加入圖片或定義字體大小就不可以了,但直接在郵件內容打上 html 又會直接給收件者顯示 html 標記語言,而不是預期的效果。
其實使用 mail() 函式發送 HTML 郵件,關鍵在 header 參數。請看以下例子,大致內容與上面的例子一樣:
testing This is a html email.';mail("testing@testing.com", "testing email", $email_content, "From:My Name
\nContent-Type:text/html");
?>你可以看到,以上例子的郵件內容使用了 html 標記語言,而在 header 參數那裡加入了 "Content-Type:text/html"。
你可能感興趣的內容