PHP mail()
函式用於在PHP中傳送電子郵件。 您可以使用PHP mail()
函式來傳送簡訊,HTML訊息和附件與訊息。
語法
$to
:指定郵件的接收者或接收者。 接收器必須指定以下格式之一。
$subject
: 代表郵件的主題。$message
: 表示要傳送的郵件的訊息。$additional_headers
(可選):指定附加頭,如From
,CC
,BCC
等。額外的附加頭也應該用CRLF(\r\n
)分隔。注意:訊息的每一行應使用CRLF(
\r\n
)分隔,並且行不應大於70
個字元。
檔案:mailer.php
<?php
ini_set("sendmail_from", "[email protected]");
$to = "[email protected]";//change receiver address
$subject = "This is subject";
$message = "This is simple text message.";
$header = "From:[email protected] \r\n";
$result = mail ($to,$subject,$message,$header);
if( $result == true ){
echo "Message sent successfully...";
}else{
echo "Sorry, unable to send mail...";
}
?>
如果在執行伺服器上執行此程式碼,它將向指定的接收方傳送電子郵件。
要傳送HTML訊息,您需要在訊息標題中提及Content-type text/html
。
<?php
$to = "[email protected]";//change receiver address
$subject = "This is subject";
$message = "<h1>This is HTML heading</h1>";
$header = "From:[email protected] \r\n";
$header .= "MIME-Version: 1.0 \r\n";
$header .= "Content-type: text/html;charset=UTF-8 \r\n";
$result = mail ($to,$subject,$message,$header);
if( $result == true ){
echo "Message sent successfully...";
}else{
echo "Sorry, unable to send mail...";
}
?>
要使用附件傳送訊息,您需要提及許多標題資訊,在下面給出的範例中使用。
<?php
$to = "[email protected]";
$subject = "This is subject";
$message = "This is a text message.";
# Open a file
$file = fopen("/tmp/test.txt", "r" );//change your file location
if( $file == false )
{
echo "Error in opening file";
exit();
}
# Read the file into a variable
$size = filesize("/tmp/test.txt");
$content = fread( $file, $size);
# encode the data for safe transit
# and insert \r\n after every 76 chars.
$encoded_content = chunk_split( base64_encode($content));
# Get a random 32 bit number using time() as seed.
$num = md5( time() );
# Define the main headers.
$header = "From:[email protected]\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; ";
$header .= "boundary=$num\r\n";
$header .= "--$num\r\n";
# Define the message section
$header .= "Content-Type: text/plain\r\n";
$header .= "Content-Transfer-Encoding:8bit\r\n\n";
$header .= "$message\r\n";
$header .= "--$num\r\n";
# Define the attachment section
$header .= "Content-Type: multipart/mixed; ";
$header .= "name=\"test.txt\"\r\n";
$header .= "Content-Transfer-Encoding:base64\r\n";
$header .= "Content-Disposition:attachment; ";
$header .= "filename=\"test.txt\"\r\n\n";
$header .= "$encoded_content\r\n";
$header .= "--$num--";
# Send email now
$result = mail ( $to, $subject, "", $header );
if( $result == true ){
echo "Message sent successfully...";
}else{
echo "Sorry, unable to send mail...";
}
?>