- PHP 教程
- PHP - 首頁
- PHP - 簡介
- PHP - 安裝
- PHP - 歷史
- PHP - 特性
- PHP - 語法
- PHP - Hello World
- PHP - 註釋
- PHP - 變數
- PHP - Echo/Print
- PHP - var_dump
- PHP - $ 和 $$ 變數
- PHP - 常量
- PHP - 魔術常量
- PHP - 資料型別
- PHP - 型別轉換
- PHP - 型別強制轉換
- PHP - 字串
- PHP - 布林值
- PHP - 整數
- PHP - 檔案與I/O
- PHP - 數學函式
- PHP - Heredoc & Nowdoc
- PHP - 複合型別
- PHP - 檔案包含
- PHP - 日期與時間
- PHP - 標量型別宣告
- PHP - 返回型別宣告
- PHP 運算子
- PHP - 運算子
- PHP - 算術運算子
- PHP - 比較運算子
- PHP - 邏輯運算子
- PHP - 賦值運算子
- PHP - 字串運算子
- PHP - 陣列運算子
- PHP - 條件運算子
- PHP - 展開運算子
- PHP - 空值合併運算子
- PHP - 比較運算子(太空船運算子)
- PHP 控制語句
- PHP - 決策
- PHP - If…Else 語句
- PHP - Switch 語句
- PHP - 迴圈型別
- PHP - For 迴圈
- PHP - Foreach 迴圈
- PHP - While 迴圈
- PHP - Do…While 迴圈
- PHP - Break 語句
- PHP - Continue 語句
- PHP 函式
- PHP - 函式
- PHP - 函式引數
- PHP - 按值傳遞
- PHP - 按引用傳遞
- PHP - 預設引數
- PHP - 具名引數
- PHP - 可變引數
- PHP - 返回值
- PHP - 傳遞函式
- PHP - 遞迴函式
- PHP - 型別提示
- PHP - 變數作用域
- PHP - 嚴格型別
- PHP - 匿名函式
- PHP - 箭頭函式
- PHP - 可變函式
- PHP - 區域性變數
- PHP - 全域性變數
- PHP 超全域性變數
- PHP - 超全域性變數
- PHP - $GLOBALS
- PHP - $_SERVER
- PHP - $_REQUEST
- PHP - $_POST
- PHP - $_GET
- PHP - $_FILES
- PHP - $_ENV
- PHP - $_COOKIE
- PHP - $_SESSION
- PHP 檔案處理
- PHP - 檔案處理
- PHP - 開啟檔案
- PHP - 讀取檔案
- PHP - 寫入檔案
- PHP - 檔案是否存在
- PHP - 下載檔案
- PHP - 複製檔案
- PHP - 追加檔案
- PHP - 刪除檔案
- PHP - 處理CSV檔案
- PHP - 檔案許可權
- PHP - 建立目錄
- PHP - 列出檔案
- 面向物件PHP
- PHP - 面向物件程式設計
- PHP - 類和物件
- PHP - 建構函式和解構函式
- PHP - 訪問修飾符
- PHP - 繼承
- PHP - 類常量
- PHP - 抽象類
- PHP - 介面
- PHP - Traits
- PHP - 靜態方法
- PHP - 靜態屬性
- PHP - 名稱空間
- PHP - 物件迭代
- PHP - 封裝
- PHP - final 關鍵字
- PHP - 過載
- PHP - 克隆物件
- PHP - 匿名類
- PHP Web 開發
- PHP - Web 概念
- PHP - 表單處理
- PHP - 表單驗證
- PHP - 表單郵件/URL
- PHP - 完整表單
- PHP - 檔案包含
- PHP - GET & POST
- PHP - 檔案上傳
- PHP - Cookie
- PHP - Session
- PHP - Session 選項
- PHP - 傳送郵件
- PHP - 輸入過濾
- PHP - Post-Redirect-Get (PRG)
- PHP - 快閃記憶體訊息
- PHP 高階
- PHP - MySQL
- PHP.INI 檔案配置
- PHP - 陣列解構
- PHP - 程式碼規範
- PHP - 正則表示式
- PHP - 錯誤處理
- PHP - Try…Catch
- PHP - Bug 除錯
- PHP - 針對C語言開發者
- PHP - 針對Perl開發者
- PHP - 框架
- PHP - Core PHP vs 框架
- PHP - 設計模式
- PHP - 過濾器
- PHP - JSON
- PHP - 異常
- PHP - 特殊型別
- PHP - 雜湊
- PHP - 加密
- PHP - is_null() 函式
- PHP - 系統呼叫
- PHP - HTTP 認證
- PHP - 交換變數
- PHP - Closure::call()
- PHP - 過濾後的 unserialize()
- PHP - IntlChar
- PHP - CSPRNG
- PHP - 預期
- PHP - use 語句
- PHP - 整數除法
- PHP - 已棄用的特性
- PHP - 已移除的擴充套件和SAPI
- PHP - PEAR
- PHP - CSRF
- PHP - FastCGI 程序
- PHP - PDO 擴充套件
- PHP - 內建函式
- PHP 有用資源
- PHP - 速查表
- PHP - 問答
- PHP - 快速指南
- PHP - 線上編譯器
- PHP - 有用資源
- PHP - 討論
PHP - 傳送郵件
傳送電子郵件的功能是典型的PHP驅動Web應用程式中常用的功能之一。您希望透過PHP應用程式本身傳送包含通知、更新和其他通訊的電子郵件給您的註冊使用者,而不是使用不同的郵件服務。您可以透過採用本章中描述的技術,將此功能新增到您的PHP應用程式中。
PHP有一個內建的mail()函式來發送電子郵件。但是,您需要正確配置“php.ini”設定才能這樣做。首先,您必須知道您正在使用的Web託管平臺的SMTP域。例如,如果您的網站託管在GoDaddy託管服務上,則SMTP域為“smtp.secureserver.net”,您應該在配置中使用它。
如果您使用GoDaddy的基於Windows的託管,則應確保在php.ini檔案中啟用了兩個指令。第一個稱為SMTP,它定義您的電子郵件伺服器地址。第二個稱為sendmail_from,它定義您自己的電子郵件地址。
Windows的配置如下所示:
[mail function] ; For Win32 only. SMTP = smtp.secureserver.net ; For win32 only sendmail_from = webmaster@tutorialspoint.com
Linux使用者只需讓PHP知道其sendmail應用程式的位置即可。應將路徑和任何所需的開關指定給sendmail_path指令。
Linux的配置如下所示:
[mail function] ; For Win32 only. SMTP = ; For win32 only sendmail_from = ; For Unix only sendmail_path = /usr/sbin/sendmail -t -i
PHP中的mail()函式需要三個必填引數,它們指定收件人的電子郵件地址、郵件主題和實際郵件,此外還有另外兩個可選引數。
mail( to, subject, message, headers, parameters );
引數
to − 必需。指定電子郵件的接收者/接收者
subject − 必需。指定電子郵件的主題。此引數不能包含任何換行符
message − 必需。定義要傳送的訊息。每一行應以LF(\n)分隔。行數不應超過70個字元
headers − 可選。指定其他標頭,如From、Cc和Bcc。其他標頭應以CRLF(\r\n)分隔
parameters − 可選。向sendmail程式指定附加引數
可以使用逗號分隔的列表,在mail()函式的第一個引數中指定多個收件人。
傳送HTML郵件
使用PHP傳送文字訊息時,所有內容都將被視為純文字。即使您在文字訊息中包含HTML標籤,它也會顯示為純文字,並且HTML標籤不會根據HTML語法進行格式化。但是PHP提供了將HTML訊息作為實際HTML訊息傳送的選項。
傳送電子郵件時,您可以指定Mime版本、內容型別和字元集來發送HTML電子郵件。
示例
以下示例演示如何將HTML電子郵件訊息傳送給“xyz@somedomain.com”,並將其抄送至“afgh@somedomain.com”。您可以編寫此程式,使其可以接收使用者的所有內容,然後傳送電子郵件。
它應該接收使用者的所有內容,然後傳送電子郵件。
<?php
$to = "xyz@somedomain.com";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:abc@somedomain.com \r\n";
$header .= "Cc:afgh@somedomain.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>
它將產生以下輸出:
Message could not be sent... sh: 1: /usr/sbin/sendmail: not found
從本地主機發送郵件
上述呼叫PHP mail()的方法可能無法在您的本地主機上執行。在這種情況下,有一種替代的傳送電子郵件的解決方案。您可以使用PHPMailer透過本地主機的SMTP傳送電子郵件。
PHPMailer是一個開源庫,用於連線SMTP來發送電子郵件。您可以從PEAR或Composer儲存庫下載它,也可以從https://github.com/PHPMailer/PHPMailer下載。從此處下載ZIP檔案,並將PHPMailer資料夾的內容複製到PHP配置中指定的include_path目錄之一,並手動載入每個類檔案。
示例
使用以下PHP指令碼使用PHPMailer庫傳送電子郵件:
Phpmailer.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once __DIR__ . '/vendor/phpmailer/src/Exception.php';
require_once __DIR__ . '/vendor/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/vendor/phpmailer/src/SMTP.php';
require 'vendor/autoload.php';
$mail = new PHPMailer;
if(isset($_POST['send'])){
// getting post values
$fname=$_POST['fname'];
$toemail=$_POST['toemail'];
$subject=$_POST['subject'];
$message=$_POST['message'];
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'myID@gmail.com'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
// Enable TLS encryption, 'ssl' also accepted
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom(myID@gmail.com', 'My_Name');
$mail->addReplyTo(myID@gmail.com', 'My_Name');
$mail->addAddress($toemail); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$bodyContent=$message;
$mail->Subject =$subject;
$body = 'Dear'.$fname;
$body .='<p>'.$message.'</p>';
$mail->Body = $body;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
}
?>
使用以下HTML表單撰寫郵件。該表單提交到上面的phpmail.php指令碼
Email.html
<h1>PHP - Sending Email</h1> <form action="PHPmailer.php" method="post"> <label for="inputName">Name</label> <input type="text" id="inputName" name="fname" required> <label for="inputEmail">Email</label> <input type="email" id="inputEmail" name="toemail" required> <label for="inputSubject">Subject</label> <input type="text" id="inputSubject" name="subject" required> <label for="inputMessage">Message</label> <textarea id="inputMessage" name="message" rows="5" required></textarea> <button type="submit" name="send">Send</button> </form>
傳送帶附件的郵件
要傳送包含混合內容的電子郵件,應將Content-type標頭設定為multipart/mixed。然後可以在邊界內指定文字和附件部分。
邊界以兩個連字元開頭,後跟一個在郵件正文中不會出現的唯一數字。PHP函式md5()用於建立一個32位十六進位制數字來建立唯一數字。表示電子郵件最後一部分的最終邊界也必須以兩個連字元結尾。
示例
請看下面的例子:
<?php
// request variables
$from = $_REQUEST["from"];
$emaila = $_REQUEST["emaila"];
$filea = $_REQUEST["filea"];
if ($filea) {
function mail_attachment ($from , $to, $subject, $message, $attachment){
$fileatt = $attachment; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type
$start = strrpos($attachment, '/') == -1 ?
strrpos($attachment, '//') : strrpos($attachment, '/')+1;
// Filename that will be used for the file as the attachment
$fileatt_name = substr($attachment, $start,
strlen($attachment));
$email_from = $from; // Who the email is from
$subject = "New Attachment Message";
$email_subject = $subject; // The Subject of the email
$email_txt = $message; // Message that the email has in it
$email_to = $to; // Who the email is to
$headers = "From: ".$email_from;
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$msg_txt="\n\n You have recieved a new attachment message from $from";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . "
boundary=\"{$mime_boundary}\"";
$email_txt .= $msg_txt;
$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" . "Content-Type:text/html;
charset = \"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" .
$email_txt . "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" .
" name = \"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" .
//" filename = \"{$fileatt_name}\"\n" . "Content-Transfer-Encoding:
"base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n";
$ok = mail($email_to, $email_subject, $email_message, $headers);
if($ok) {
echo "File Sent Successfully.";
// delete a file after attachment sent.
unlink($attachment);
} else {
die("Sorry but the email could not be sent. Please go back and try again!");
}
}
move_uploaded_file($_FILES["filea"]["tmp_name"],
'temp/'.basename($_FILES['filea']['name']));
mail_attachment("$from", "youremailaddress@gmail.com",
"subject", "message", ("temp/".$_FILES["filea"]["name"]));
}
?>
<html>
<head>
<script language = "javascript" type = "text/javascript">
function CheckData45() {
with(document.filepost) {
if(filea.value ! = "") {
document.getElementById('one').innerText = "Attaching File ... Please Wait";
}
}
}
</script>
</head>
<body>
<table width = "100%" height = "100%" border = "0"
cellpadding = "0" cellspacing = "0">
<tr>
<td align = "center">
<form name = "filepost" method = "post"
action = "file.php" enctype = "multipart/form-data" id = "file">
<table width = "300" border = "0" cellspacing = "0"
cellpadding = "0">
<tr valign = "bottom">
<td height = "20">Your Name:</td>
</tr>
<tr>
<td><input name = "from" type = "text" id = "from" size = "30"></td>
</tr>
<tr valign = "bottom">
<td height = "20">Your Email Address:</td>
</tr>
<tr>
<td class = "frmtxt2"><input name = "emaila" type = "text" id = "emaila" size = "30"></td>
</tr>
<tr>
<td height = "20" valign = "bottom">Attach File:</td>
</tr>
<tr valign = "bottom">
<td valign = "bottom"><input name = "filea" type = "file" id = "filea" size = "16"></td>
</tr>
<tr>
<td height = "40" valign = "middle">
<input name = "Reset2" type = "reset" id = "Reset2" value = "Reset">
<input name = "Submit2" type = "submit" value = "Submit" onClick = "return CheckData45()">
</td>
</tr>
</table>
</form>
<center>
<table width = "400">
<tr>
<td id = "one"></td>
</tr>
</table>
</center>
</td>
</tr>
</table>
</body>
</html>
它將產生以下輸出: