在PHP中发送电子邮件

从脚本发送电子邮件是Web应用程序中非常有用的功能。
大多数使用电子邮件发送功能向用户发送通知。
如果使用PHP或者使用PHP开发的Web应用程序,则使用PHP从脚本发送电子邮件非常容易。

PHP提供了一种从发送电子邮件的简单方法。
我们可以在PHP中发送带有Mail()函数的文本或者HTML电子邮件。
但有时需要扩展电子邮件功能以发送与邮件的附件。
在本教程中,我们将展示如何在PHP中发送带有附件的电子邮件。

在示例脚本中,我们将简单地将包括任何类型的文件作为附件(如图像,.doc,.docx,.pdf,.txt等)发送文本或者HTML电子邮件。

使用附件发送HTML电子邮件

具有一些MIME类型标头的PHP邮件()函数可用于在PHP中发送带有附件的电子邮件。
在以下示例代码中,MIME和Content-Type标题与Mail()函数一起使用,以使用PHP向电子邮件发送附件。

  • '$to' - 收件人电子邮件地址。
  • '$from' - 发件人电子邮件地址。
  • '$fromname' - 发件人姓名。
  • '$subject' - 电子邮件的主题。
  • '$file' - 要用电子邮件添加的文件的相对路径。
  • '$HTMLContent' - 电子邮件的身体内容(文本或者HTML)。

以下脚本允许我们将两种类型的消息(文本或者HTML)与附件文件发送到电子邮件。

<?php 

//Recipient 
$to = 'recipient@example.com'; 

//Sender 
$from = 'sender@example.com'; 
$fromName = 'onitroad'; 

//Email subject 
$subject = 'PHP Email with Attachment by onitroad';  

//Attachment file 
$file = "files/onitroad.pdf"; 

//Email body content 
$htmlContent = ' 
    <h3>PHP Email with Attachment by onitroad</h3> 
    <p>This email is sent from the PHP script with attachment.</p> 
'; 

//Header for sender info 
$headers = "From: $fromName"." <".$from.">"; 

//Boundary  
$semi_rand = md5(time());  
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";  

//Headers for attachment  
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 

//Multipart boundary  
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" . 
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";  

//Preparing attachment 
if(!empty($file) > 0){ 
    if(is_file($file)){ 
        $message .= "--{$mime_boundary}\n"; 
        $fp =    @fopen($file,"rb"); 
        $data =  @fread($fp,filesize($file)); 

        @fclose($fp); 
        $data = chunk_split(base64_encode($data)); 
        $message .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\n" .  
        "Content-Description: ".basename($file)."\n" . 
        "Content-Disposition: attachment;\n" . " filename=\"".basename($file)."\"; size=".filesize($file).";\n" .  
        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; 
    } 
} 
$message .= "--{$mime_boundary}--"; 
$returnpath = "-f" . $from; 

//Send email 
$mail = @mail($to, $subject, $message, $headers, $returnpath);  

//Email sending status 
echo $mail?"<h1>Email Sent Successfully!</h1>":"<h1>Email sending failed.</h1>"; 

?>

示例脚本允许我们向电子邮件发送单个附件,发送带有多个附件的电子邮件,请按照本教程发送具有多个PHP中的附件的发送电子邮件

向多个收件人发送电子邮件:
我们可以使用CC和BCC标头立即向多个收件人发送电子邮件。
使用CC和BCC标头用于在PHP中的多个收件人附件发送电子邮件。

$headers .= "\nCc: mail@example.com"; 
$headers .= "\nBcc: mail@example.com";
日期:2020-06-02 22:15:59 来源:oir作者:oir