PHP - 使用 PHP 发送电子邮件


必须在php.ini文件中正确配置 PHP,并包含系统如何发送电子邮件的详细信息。打开/etc/目录中的 php.ini 文件并找到标题为[邮件功能]的部分。

Windows 用户应确保提供两个指令。第一个称为 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 );

以下是每个参数的说明。

先生编号 参数及说明
1

必需的。指定电子邮件的接收者/接收者

2

主题

必需的。指定电子邮件的主题。该参数不能包含任何换行符

3

信息

必需的。定义要发送的消息。每行应该用 LF (\n) 分隔。行不应超过 70 个字符

4

标头

选修的。指定附加标头,例如 From、Cc 和 Bcc。附加标头应使用 CRLF (\r\n) 分隔

5

参数

选修的。指定发送邮件程序的附加参数

一旦调用邮件函数,PHP 将尝试发送电子邮件,如果成功则返回 true,如果失败则返回 false。

可以将多个收件人指定为逗号分隔列表中的 mail() 函数的第一个参数。

发送 HTML 电子邮件

当您使用 PHP 发送文本消息时,所有内容都将被视为简单文本。即使您在文本消息中包含 HTML 标签,它也会显示为简单文本,并且 HTML 标签不会根据 HTML 语法进行格式化。但 PHP 提供了将 HTML 消息作为实际 HTML 消息发送的选项。

发送电子邮件时,您可以指定 Mime 版本、内容类型和字符集来发送 HTML 电子邮件。

例子

以下示例将向 xyz@somedomain.com 发送一封 HTML 电子邮件,并将其复制到 afgh@somedomain.com。您可以以这样的方式编写该程序:它应该接收来自用户的所有内容,然后发送电子邮件。

<html>
   
   <head>
      <title>Sending HTML email using PHP</title>
   </head>
   
   <body>
      
      <?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...";
         }
      ?>
      
   </body>
</html>

通过电子邮件发送附件

要发送包含混合内容的电子邮件,需要将Content-type标头设置为multipart/mixed然后可以在边界内指定文本和附件部分。

边界以两个连字符开始,后跟一个唯一的数字,该数字不能出现在电子邮件的消息部分中。PHP 函数md5()用于创建 32 位十六进制数字以创建唯一编号。表示电子邮件最后部分的最终边界也必须以两个连字符结尾。

<?php
   // request variables // important
   $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;
				
         $fileatt_name = substr($attachment, $start, 
            strlen($attachment)); // Filename that will be used for the 
            file as the 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.";
            unlink($attachment); // delete a file after attachment sent.
         }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>