HOWTO · PHP

在 PHP 中使用郵件表單傳送電子郵件

本教程演示瞭如何在 PHP 中通過郵件表單傳送電子郵件。

本教程將演示安裝 sendmail 庫並通過 PHP 郵件表單傳送電子郵件。

安裝 sendmail 以在本地伺服器上從 PHP 傳送電子郵件

PHP 有一個內建函式 mail() 來傳送電子郵件。但是,在你安裝它的庫之前,此功能將不起作用。

要安裝 sendmail,請按照以下步驟操作。

  • 下載並提取 sendmail

    這裡下載 sendmail。然後將 zip 檔案解壓縮到 C:\sendmail\

  • 配置 sendmail.ini

    現在,從主 sendmail 資料夾中開啟 sendmail.ini。搜尋並設定如下配置。

    smtp_server=smtp.gmail.com
    
    smtp_port=587
    
    auth_username=The_email_from@gmail.com
    
    auth_password=Email Password
    
    force_sender=your_address@gmail.com
    

    此設定用於通過 Gmail 傳送電子郵件,你也可以從其他人或你的伺服器傳送電子郵件。

    需要在這些引數中進行設定。auth_usernameauth_password 將是你要傳送電子郵件的電子郵件和密碼。

  • 配置 php.ini

    要進行配置,請開啟 php.ini 檔案並搜尋 sendmail_path。然後將此引數設定為 C:\sendmail\sendmail.exe -t

    ; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
    ; http://php.net/sendmail-path
    sendmail_path ="C:\sendmail\sendmail.exe -t"
    

    重新啟動本地伺服器,就完成了。

  • 測試傳送電子郵件。

    你可以傳送一封帶有簡單的一行程式碼的電子郵件進行測試,如下所示。

    <?php
    mail("example@hotmail.com","Test subject", "This is a test Email");
    ?>
    

    輸出:

    測試郵件

    如你所見,輸出是傳送到指定地址的郵件。

在 PHP 中使用郵件表單建立和傳送電子郵件

首先,你必須建立一個 HTML 表單以將電子郵件資料傳送到 PHP 程式碼。使用 mail() 函式使用該資料傳送電子郵件。

例子:

<?php 
if(isset($_POST['submit']))
{
    $email_address = $_POST['email_address'];
    $subject = "This is a test email";

    $email_message = "The following message is sent in email:" . "\n\n" . $_POST['email_message'];
    mail($email_address,$subject,$email_message);
    echo "Email sent to ".$email_address;
    // You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
<!DOCTYPE html>
<head>
    <title>PHP Mail Form</title>
</head>
<body>
    <form action="" method="post">
    Email: <input type= "email" name= "email_address"><br>
    Message:<br> <textarea rows= "10" name= "email_message" cols= "50"> </textarea> <br>
    <input type= "submit" name= "submit" value= "Send Email">
    </form>
</body>
</html>

輸出:

Email sent to example@outlook.com

PHP 使用郵件表單傳送電子郵件

上面的程式碼生成了一個帶有 emailmessage 框的表單。然後,程式碼將訊息框中寫入的內容傳送到電子郵件欄位中給出的電子郵件地址。

姓名、姓氏和日期等其他欄位也可以新增到表單中,以傳送包含更多資訊的電子郵件。