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>

它將產生以下輸出

PHP Sending Emails
廣告