10.10 使用 PHP 程式寄信

  假設我們已經建立好一個表單,擁有 email、name、school、birth、note 等欄位,我們可以使用以下方法寄信:
<?php

if (!preg_match('/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i',
$_POST['email']))
    die('電子郵件信箱無效');

foreach ($_POST as $key => $value)
    $_POST[$key] = htmlentities
        ((string) $_POST[$key], ENT_QUOTES, 'UTF-8');

$_POST['note'] = nl2br($_POST['note']);

$to = $_POST['email'];

$subject = '=?UTF-8?B?'.base64_encode('網站通知信').'?=';

$body = <<<MESSAGE
<!DOCTYPE html>\r\n
<html>\r\n
<head>\r\n
    <style type='text/css'>\r\n
        table {\r\n
            border-collapse: collapse;\r\n
        }\r\n
        td {\r\n
            border: 1px solid black;\r\n
            white-space: nowrap;
        }\r\n
        td:first-child {\r\n
            width: 120px;\r\n
        }\r\n
    </style>\r\n
</head>\r\n
<body>\r\n
    <p>我們已經收到您的資料囉!您填寫的資料如下:</p>\r\n
    <table>\r\n
        <tr><td>姓名</td><td>$_POST[name]</td></tr>\r\n
        <tr><td>學校</td><td>$_POST[school]</td></tr>\r\n
        <tr><td>生日</td><td>$_POST[birth]</td></tr>\r\n
        <tr><td>備註</td><td>$_POST[note]</td></tr>\r\n
    </table>\r\n
    <p>本郵件由系統自動寄出,請勿回覆。</p>\r\n
</body>\r\n
</html>\r\n
MESSAGE;

$header = "MIME-Version: 1.0\r\n".
    "Content-type: text/html; charset=utf-8\r\n";

mail($to, $subject, $body, $header);

?>
  當然,在這之前,別忘了先安裝簡單郵件傳輸協議 (Simple Mail Transfer Protocol, SMTP) 伺服器,如此才能將信件順利寄出哦!