使用PHP Mail()发送附件?

217 php

我需要发送带有邮件的pdf,这可能吗?

$to = "xxx";
$subject = "Subject" ;
$message = 'Example message with <b>html</b>';
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: xxx <xxx>' . "\r\n";
mail($to,$subject,$message,$headers);
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

SDC*_*SDC 297

我在评论中同意@MihaiIorga - 使用PHPMailer脚本.你听起来像是在拒绝它,因为你想要更简单的选择.相信我,与使用PHP的内置函数自己完成相比,PHPMailer 一个非常大的选择mail().PHP的mail()功能确实不是很好.

要使用PHPMailer:

  • 从这里下载PHPMailer脚本:http://github.com/PHPMailer/PHPMailer
  • 提取存档并将脚本的文件夹复制到项目中的方便位置.
  • 包括主脚本文件 - require_once('path/to/file/class.phpmailer.php');

现在,发送附带电子邮件的过程非常困难,非常简单:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$email = new PHPMailer();
$email->SetFrom('you@example.com', 'Your Name'); //Name is optional
$email->Subject   = 'Message Subject';
$email->Body      = $bodytext;
$email->AddAddress( 'destinationaddress@example.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();
Run Code Online (Sandbox Code Playgroud)

这只是一条线$email->AddAttachment();- 你不能要求更容易.

如果你使用PHP的mail()函数来做,那么你将编写代码堆栈,并且你可能有很多很难找到错误.

  • 我发现这个问题寻找如何使用`mail()`函数添加附件的答案.这个答案对我没有帮助. (91认同)
  • 这不是问题的答案.如何使用PHPMailer发送附件不是如何使用PHP的mail()发送附件. (13认同)
  • PHPMAILER 对许多人来说似乎是一个很好的简单方法。但是使用它需要不必要地导入另一个值得信任的东西(即 PHPMailer 中没有错误/等)。要不盲目相信一个人需要查看至少 3155 行 sloc (115.456 kb) 的代码。鉴于使用答案纯粹的 mail() 替代方案,这似乎是一个更糟糕的权衡。替代答案可以使用少于 100 个 sloc。不喜欢“我想要 A”的答案是“不,使用 B 更好”。其他答案告诉“A 是这样完成的”。 (5认同)
  • 这个答案也忽略了项目使用的许可证.通过使用PHPMailer,您必须确保从源中排除包以防止其LGPL许可证出现问题. (4认同)
  • 我是一样的 - 想使用mail()只是因为我已经在我的代码中使用它了.PHPMAILER花了我不到5分钟的时间来发送附件! (3认同)
  • 如果有人向您询问有关 Bing 的信息;你不是说忘记它只是使用谷歌.. (2认同)

Pra*_*han 179

您可以尝试使用以下代码:

    $filename = 'myfile';
    $path = 'your path goes here';
    $file = $path . "/" . $filename;

    $mailto = 'mail@mail.com';
    $subject = 'Subject';
    $message = 'My message';

    $content = file_get_contents($file);
    $content = chunk_split(base64_encode($content));

    // a random hash will be necessary to send mixed content
    $separator = md5(time());

    // carriage return type (RFC)
    $eol = "\r\n";

    // main header (multipart mandatory)
    $headers = "From: name <test@test.com>" . $eol;
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    $headers .= "This is a MIME encoded message." . $eol;

    // message
    $body = "--" . $separator . $eol;
    $body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    $body .= "Content-Transfer-Encoding: 8bit" . $eol;
    $body .= $message . $eol;

    // attachment
    $body .= "--" . $separator . $eol;
    $body .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
    $body .= "Content-Transfer-Encoding: base64" . $eol;
    $body .= "Content-Disposition: attachment" . $eol;
    $body .= $content . $eol;
    $body .= "--" . $separator . "--";

    //SEND Mail
    if (mail($mailto, $subject, $body, $headers)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
        print_r( error_get_last() );
    }
Run Code Online (Sandbox Code Playgroud)

编辑于2018年6月14日

在某些电子邮件提供商使用中更易读

$body .= $eol . $message . $eol . $eol;$body .= $eol . $content . $eol . $eol;

  • 来自 PHPMailer 的文档......“正确格式化电子邮件非常困难。有无数重叠的 RFC,需要严格遵守极其复杂的格式和编码规则 - 您可以在网上找到的绝大多数代码直接使用 mail() 函数简直是大错特错!” ...这是真的!我已经使用类似这个答案的东西来发送带有附件的邮件并且它起作用了!几天后才发现,虽然 Gmail 显示附件很好,但其他提供商直接在邮件中内嵌显示 base64 内容。 (2认同)

Sim*_*ele 131

对于PHP 5.5.27安全更新

$file = $path.$filename;
$content = file_get_contents( $file);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);

// header
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";

// message & attachment
$nmessage = "--".$uid."\r\n";
$nmessage .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$nmessage .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$nmessage .= $message."\r\n\r\n";
$nmessage .= "--".$uid."\r\n";
$nmessage .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$nmessage .= "Content-Transfer-Encoding: base64\r\n";
$nmessage .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$nmessage .= $content."\r\n\r\n";
$nmessage .= "--".$uid."--";

if (mail($mailto, $subject, $nmessage, $header)) {
    return true; // Or do something here
} else {
  return false;
}
Run Code Online (Sandbox Code Playgroud)

  • @乔恩.$ filename,是文件的实际名称,$ path是没有文件名的实际文件路径.我认为变量具有足够的描述性来声明和制度化 (3认同)
  • 请注意发送多个附件的人 - 使用`$ nmessage.=" - ".$ uid."\ r \n";`单独的MIME部分,在最终的MIME部分之后,使用`$ nmessage.=" - " .$ uid." - ";`(如上图所示). (3认同)
  • 这是有史以来最好的答案!!!!!!! 谢谢伙伴....花了我2天才找到这个答案! (2认同)
  • 在努力让愚蠢的phpmailer工作起来之后,这终于奏效了. (2认同)
  • 这是一个非常清晰干净的答案。当 Outlook、Gmail 等接收到时,它就可以工作。简洁的答案。如果你能更新HTML消息部分,这将变得更加完整。 (2认同)

Mat*_*son 21

Swiftmailer是另一个易于使用的脚本,可自动防止电子邮件注入,并使附件变得轻而易举.我也强烈反对使用PHP的内置mail()函数.

使用:

  • 下载Swiftmailer,并将lib文件夹放在项目中
  • 使用包含主文件 require_once 'lib/swift_required.php';

现在在需要邮件时添加代码:

// Create the message
$message = Swift_Message::newInstance()
    ->setSubject('Your subject')
    ->setFrom(array('webmaster@mysite.com' => 'Web Master'))
    ->setTo(array('receiver@example.com'))
    ->setBody('Here is the message itself')
    ->attach(Swift_Attachment::fromPath('myPDF.pdf'));

//send the message          
$mailer->send($message);
Run Code Online (Sandbox Code Playgroud)

可以在Swiftmailer Docs中找到更多信息和选项.

  • 因为你提议dwonload第三方库,我想 (6认同)

Bas*_*ith 16

要发送带附件的电子邮件,我们需要使用multipart/mixed MIME类型,指定混合类型将包含在电子邮件中.此外,我们希望使用multipart/alternative MIME类型来发送电子邮件的纯文本和HTML版本.看看示例:

<?php 
//define the receiver of the email 
$to = 'youraddress@example.com'; 
//define the subject of the email 
$subject = 'Test email with attachment'; 
//create a boundary string. It must be unique 
//so we use the MD5 algorithm to generate a random hash 
$random_hash = md5(date('r', time())); 
//define the headers we want passed. Note that they are separated with \r\n 
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com"; 
//add boundary string and mime type specification 
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; 
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip'))); 
//define the body of the message. 
ob_start(); //Turn on output buffering 
?> 
--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/plain; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

Hello World!!! 
This is simple text email message. 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/html; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2> 
<p>This is something with <b>HTML</b> formatting.</p> 

--PHP-alt-<?php echo $random_hash; ?>-- 

--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: application/zip; name="attachment.zip"  
Content-Transfer-Encoding: base64  
Content-Disposition: attachment  

<?php echo $attachment; ?> 
--PHP-mixed-<?php echo $random_hash; ?>-- 

<?php 
//copy current buffer contents into $message variable and delete current output buffer 
$message = ob_get_clean(); 
//send the email 
$mail_sent = @mail( $to, $subject, $message, $headers ); 
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed"; 
?>
Run Code Online (Sandbox Code Playgroud)

如您所见,发送带附件的电子邮件很容易实现.在前面的示例中,我们有多部分/混合MIME类型,在其中我们有多部分/替代MIME类型,指定电子邮件的两个版本.要在我们的消息中包含附件,我们将指定文件中的数据读入字符串,使用base64对其进行编码,将其拆分为较小的块以确保它与MIME规范匹配,然后将其作为附件包含在内.

取自这里.

  • 复制/粘贴我在OP评论中添加的链接中的内容 (14认同)

Aki*_*imi 8

这适合我.它也附加了多个附件.容易

<?php

if ($_POST && isset($_FILES['file'])) {
    $recipient_email = "recipient@yourmail.com"; //recepient
    $from_email = "info@your_domain.com"; //from email using site domain.
    $subject = "Attachment email from your website!"; //email subject line

    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
    $attachments = $_FILES['file'];

    //php validation
    if (strlen($sender_name) < 4) {
        die('Name is too short or empty');
    }
    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
        die('Invalid email');
    }
    if (strlen($sender_message) < 4) {
        die('Too short message! Please enter something');
    }

    $file_count = count($attachments['name']); //count total files attached
    $boundary = md5("specialToken$4332"); // boundary token to be used

    if ($file_count > 0) { //if attachment exists
        //header
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "From:" . $from_email . "\r\n";
        $headers .= "Reply-To: " . $sender_email . "" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";

        //message text
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($sender_message));

        //attachments
        for ($x = 0; $x < $file_count; $x++) {
            if (!empty($attachments['name'][$x])) {

                if ($attachments['error'][$x] > 0) { //exit script and output error if we encounter any
                    $mymsg = array(
                        1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
                        2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                        3 => "The uploaded file was only partially uploaded",
                        4 => "No file was uploaded",
                        6 => "Missing a temporary folder");
                    die($mymsg[$attachments['error'][$x]]);
                }

                //get file info
                $file_name = $attachments['name'][$x];
                $file_size = $attachments['size'][$x];
                $file_type = $attachments['type'][$x];

                //read file 
                $handle = fopen($attachments['tmp_name'][$x], "r");
                $content = fread($handle, $file_size);
                fclose($handle);
                $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                $body .= "--$boundary\r\n";
                $body .= "Content-Type: $file_type; name=" . $file_name . "\r\n";
                $body .= "Content-Disposition: attachment; filename=" . $file_name . "\r\n";
                $body .= "Content-Transfer-Encoding: base64\r\n";
                $body .= "X-Attachment-Id: " . rand(1000, 99999) . "\r\n\r\n";
                $body .= $encoded_content;
            }
        }
    } else { //send plain email otherwise
        $headers = "From:" . $from_email . "\r\n" .
                "Reply-To: " . $sender_email . "\n" .
                "X-Mailer: PHP/" . phpversion();
        $body = $sender_message;
    }

    $sentMail = @mail($recipient_email, $subject, $body, $headers);
    if ($sentMail) { //output success or failure messages
        die('Thank you for your email');
    } else {
        die('Could not send mail! Please check your PHP mail configuration.');
    }
}
?>
Run Code Online (Sandbox Code Playgroud)


Ped*_*ito 6

经过一段时间与格式错误的附件挣扎后,这是我最终使用的代码:

$email = new PHPMailer();
$email->From      = 'from@somedomain.com';
$email->FromName  = 'FromName';
$email->Subject   = 'Subject';
$email->Body      = 'Body';
$email->AddAddress( 'to@somedomain.com' );
$email->AddAttachment( "/path/to/file" , "filename.ext", 'base64', 'application/octet-stream' );
$email->Send();
Run Code Online (Sandbox Code Playgroud)


Irs*_*han 5

工作理念:

if (isset($_POST['submit'])) {
    $mailto = $_POST["mailTo"];
    $from_mail = $_POST["fromEmail"];
    $replyto = $_POST["fromEmail"];
    $from_name = $_POST["fromName"];
    $message = $_POST["message"];
    $subject = $_POST["subject"];

    $filename = $_FILES["fileAttach"]["name"];
    $content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));

    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: " . $from_name . " <" . $from_mail . ">\r\n";
    $header .= "Reply-To: " . $replyto . "\r\n";

    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--" . $uid . "\r\n";

// You add html "Content-type: text/html; charset=utf-8\n" or for Text "Content-type:text/plain; charset=iso-8859-1\r\n" by I.khan
    $header .= "Content-type:text/html; charset=utf-8\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";

// User Message you can add HTML if You Selected HTML content
    $header .= "<div style='color: red'>" . $message . "</div>\r\n\r\n";

    $header .= "--" . $uid . "\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n"; // For Attachment
    $header .= $content . "\r\n\r\n";
    $header .= "--" . $uid . "--";
    if (mail($mailto, $subject, "", $header)) {
        echo "<script>alert('Success');</script>"; // or use booleans here
    } else {
        echo "<script>alert('Failed');</script>";
    }
}
Run Code Online (Sandbox Code Playgroud)


omi*_*kes 5

上述答案由于指定了附件格式(application/octet-stream),因此对我都不起作用。使用application/pdfPDF文件可获得最佳效果。

<?php

// just edit these 
$to          = "email1@domain.com, email2@domain.com"; // addresses to email pdf to
$from        = "sent_from@domain.com"; // address message is sent from
$subject     = "Your PDF email subject"; // email subject
$body        = "<p>The PDF is attached.</p>"; // email body
$pdfLocation = "./your-pdf.pdf"; // file location
$pdfName     = "pdf-file.pdf"; // pdf file name recipient will get
$filetype    = "application/pdf"; // type

// creates headers and mime boundary
$eol = PHP_EOL;
$semi_rand     = md5(time());
$mime_boundary = "==Multipart_Boundary_$semi_rand";
$headers       = "From: $from$eolMIME-Version: 1.0$eol" .
    "Content-Type: multipart/mixed;$eol boundary=\"$mime_boundary\"";

// add html message body
$message = "--$mime_boundary$eol" .
    "Content-Type: text/html; charset=\"iso-8859-1\"$eol" .
    "Content-Transfer-Encoding: 7bit$eol$eol$body$eol";

// fetches pdf
$file = fopen($pdfLocation, 'rb');
$data = fread($file, filesize($pdfLocation));
fclose($file);
$pdf = chunk_split(base64_encode($data));

// attaches pdf to email
$message .= "--$mime_boundary$eol" .
    "Content-Type: $filetype;$eol name=\"$pdfName\"$eol" .
    "Content-Disposition: attachment;$eol filename=\"$pdfName\"$eol" .
    "Content-Transfer-Encoding: base64$eol$eol$pdf$eol--$mime_boundary--";

// Sends the email
if(mail($to, $subject, $message, $headers)) {
    echo "The email was sent.";
}
else {
    echo "There was an error sending the mail.";
}
Run Code Online (Sandbox Code Playgroud)