如何使用 PHP 将多个文件作为电子邮件附件发送?

Susan Sarandon
发布: 2024-11-02 21:51:02
原创
708 人浏览过

How to send multiple files as attachments in an email using PHP?

在 PHP 中通过电子邮件附加和发送多个文件

最初的任务是修改只能发送一个文件附件的代码以发送两个文件附件或更多文件。此修订后的代码通过允许在电子邮件中发送多个文件附件来满足此要求:

<code class="php"><form action="#" method="POST" enctype="multipart/form-data">
    <input type="file" name="csv_file[]" /><br>
    <input type="file" name="csv_file[]" /><br>
    <input type="file" name="csv_file[]" /><br>
    <input type="submit" name="upload" value="Upload" /><br>
</form>

<?php

if($_POST) {
    // Create arrays for file information
    $ftype = $_FILES['csv_file']['type'];
    $fname = $_FILES['csv_file']['name'];

    // Define files to be attached
    $files = $fname;

    // Email fields
    $to = "recipient@example.com";
    $from = "sender@example.com";
    $subject = "Attachments";
    $message = "Email with attached files";
    $headers = "From: $from";

    // Set MIME boundary
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

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

    // Build multipart message
    $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";

    // Prepare each attachment
    foreach ($files as $key => $value) {
        $file = fopen($value, "rb");
        $data = fread($file, filesize($value));
        fclose($file);
        $data = chunk_split(base64_encode($data));
        $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$fname[$key]\"\n" .
        "Content-Disposition: attachment;\n" . " filename=\"$fname[$key]\"\n" .
        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
        $message .= "--{$mime_boundary}\n";
    }

    // Send email
    $ok = @mail($to, $subject, $message, $headers);
    if ($ok) {
        echo "<p>Email sent to $to!</p>";
    } else {
        echo "<p>Email could not be sent!</p>";
    }
}

?></code>
登录后复制

以上是如何使用 PHP 将多个文件作为电子邮件附件发送?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板