首頁 > 後端開發 > php教程 > 如何使用 PHP 將多個文件作為電子郵件附件發送?

如何使用 PHP 將多個文件作為電子郵件附件發送?

Susan Sarandon
發布: 2024-11-02 21:51:02
原創
760 人瀏覽過

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
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板