Multiple Mail Attachments in PHP

感情迁移 提交于 2019-12-08 12:48:04

问题


I was wondering if I could pick your brain about something.

I have a mail script on my site that I can use to send emails with a single attachment. Sending a single attachment works just fine.

I want to be able to send an email with multiple attachments and I am running into problems doing so.

This is the file selection box I have in the form:

<input type="file" name="attachment[]" id="attachment[]" multiple onfocus="this.style.backgroundColor='#e7e7e7'" onblur="this.style.backgroundColor='#ffffff'"/>

Then, when the files are selected this is the php that handles it:

if (!empty($_FILES['attachment']['name'])) 
    {
        if(count($_FILES['attachment']['name'])>0) 
        {
            $count = 0;
            foreach ($_FILES['attachment']['name'] as $file) 
            {
                $name_of_file = $_FILES['attachment']['name'][$count];
                $file_name = $guid." - ".$name_of_file;
                $temp_name = $_FILES['attachment']['tmp_name'][$count];
                $file_type = $_FILES['attachment']['type'][$count];
                $file_size = $_FILES['attachment']['size'][$count];
                $count++;

                if ($file_size > 2048000)
                {
                    header ("refresh: 5; url=attach.php");
                    include ("header.php");
                    echo "File size is to big. Size must be no bigger than 2Mb. Please go <a href='attach.php'>back</a>";
                    include ("footer.php");
                    exit;
                }
                else
                {
                    $pics = array(".bmp", ".gif", ".jpg", "jpeg", ".png"); //5
                    $docs = array(".doc", "docx", ".odt", ".pdf", ".ppt", "pptx", ".rtf", ".txt", ".xls", "xlsx"); //10
                    $misc = array(".csv", ".htm", "html", ".php", ".pkt", ".rar", ".sql", ".xpi", ".zip"); //9

                    $base = basename($file_name);
                    $extension = substr($base, strlen($base)-4, strlen($base));
                    $extension = strtolower($extension);

                    if (in_array($extension,$pics))
                    {
                        $target = "".FILES."/".FUP_PICS."/";
                    }

                    if (in_array($extension,$docs))
                    {
                        $target = "".FILES."/".FUP_DOCS."/";
                    }

                    if (in_array($extension,$misc))
                    {
                        $target = "".FILES."/".FUP_MISC."/";
                    }

                    $target = $target.$base;

                    $allowed_extensions = array(".bmp", ".csv", ".doc", "docx", ".gif", ".htm", "html",
                                                ".jpg", ".JPG", "jpeg", "JPEG", ".odt", ".pdf", ".php", ".pkt", ".png", ".ppt", "pptx",
                                                ".rtf", ".sql", ".txt", ".xls", "xlsx", ".zip"
                                                );

                    if(in_array($extension,$allowed_extensions)) 
                    {
                        $from = mysql_real_escape_string($_POST['from']);
                        $emailto = mysql_real_escape_string($_POST['emailto']);
                        $bcc = mysql_real_escape_string($_POST['bcc']);
                        $subject = htmlspecialchars($_POST['subject']);
                        $message = htmlspecialchars($_POST['message'], ENT_NOQUOTES);
                        $message1 = htmlspecialchars_decode($_POST['message'], ENT_QUOTES);
                        if ($sendhash == 'Y')
                        {
                            $message1 .= "\n\nThe following is your unique message ID: ";
                            $message1 .= $guid;
                            $message1 .= "\n\nAttachment has been scanned for viruses and is virus free.";
                            $message1 .= "\n\nPlease make sure the first part of the file name matches the unique message ID. If it does not, please DO NOT open the file";
                            $message1 .= "\n\nTo verify the validity of the message, click the link below or copy and paste it into your browser:";
                            $message1 .= "\n\n ";
                            $message1 .= HTTP_PATH;
                            $message1 .= "verify.php?uid=";
                            $message1 .= urlencode($guid);
                            $message1 .= "\n\nPlease note, verification link expires on ";
                            $message1 .= $expirydate;
                        }
                        else
                        {
                        }
                        $message1 .= "\n\n--\nSent from Chris' Address Book";

                        foreach ($file as $files)
                        {
                        $files = $temp_name;
                        $content = chunk_split(base64_encode(file_get_contents($file)));
                        $uid = md5(uniqid(time()));

                        $header = "From: ".$from."\r\n";
                        $header .= "Reply-To: ".$from."\r\n";
                        $header .= "Bcc: ".$bcc."\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";
                        $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
                        $header .= $message1."\r\n";

                        $header .= "--".$uid."\r\n";
                        $header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
                        $header .= "Content-Transfer-Encoding: base64\r\n";
                        $header .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
                        $header .= $content."\r\n";
                        }

                        if ($_POST['emailto'] == '')
                        {
                            $sqlp=mysql_query("SELECT * FROM ".PERSON." JOIN contact on contact.personID = person.adbkid WHERE email1 = '$bcc' OR email2 = '$bcc'");
                            $num=mysql_numrows($sqlp);
                        }
                        else
                        {
                            $sqlp=mysql_query("SELECT * FROM ".PERSON." JOIN contact on contact.personID = person.adbkid WHERE email1 = '$emailto' OR email2 = '$emailto'");
                            $num=mysql_numrows($sqlp);
                        }

                        while ($row = mysql_fetch_array($sqlp))
                        {
                            $adbkid = $row['adbkid'];
                            $id = $row['id'];
                        }

                            if ($num == 0)
                            {
                                $selfid = "EMAILSA";
                            }
                            else
                            {
                                $selfid = $adbkid;
                            }

                        if (mail($emailto, $subject, "", $header)) 
                        {
                            if ($sendhash == 'Y')
                            {
                                $sql=mysql_query("INSERT INTO ".EMAILS." (emailfrom, emailto, bcc, subject, message, getthedate, gettime, randhash, fileatt, fileext, showinsearch, expireit, showinverify, wasviewed, personID) VALUES ('$from', '$emailto', '$bcc', '$subject', '$message', '$getthedate', '$gettime', '$guid', '$file_name', '$extension', '$showinsearch', '$expireit', '$siv', '$wv', '$selfid')"); 
                                $lastid=mysql_insert_id();
                                $sqlr=mysql_query("INSERT INTO ".HASH." (randhash) VALUES ('$guid')");
                            }
                            else
                            {
                                $sql=mysql_query("INSERT INTO ".EMAILS." (emailfrom, emailto, bcc, subject, message, getthedate, gettime, fileatt, fileext, showinsearch, expireit, showinverify, wasviewed, personID) VALUES ('$from', '$emailto', '$bcc', '$subject', '$message', '$getthedate', '$gettime', '$file_name', '$extension', '$showinsearch', '$expireit', '$siv', '$wv', '$selfid')"); 
                                $lastid=mysql_insert_id();                          
                            }
                            $sqlone = "INSERT INTO ".SENTFILES." (filename, filetype, fileext, filesize, filetempname, dateadded, timeadded, fileguid, sentmailid) VALUES ('$file_name', '$file_type', '$extension', '$file_size', '$temp_name', '$getthedate', '$gettime', '$guid', '$lastid')";
                            $expire = mysql_query("UPDATE ".EMAILS." SET showinverify = 0 WHERE expireit < CURDATE()"); 
                            if (!mysql_query($sqlone,$conn))
                            {
                                die("Error: " . mysql_error().".");
                            }

                            header ("refresh: 5; url=$url");
                            include ("header.php");
                            $ful = (move_uploaded_file($temp_name, $target)) ? "".$file_name." was uploaded to ".$target."" : "".$file_name.", was not uploaded. Please try a manual upload.";
                            echo "<title>Success sending email</title>";
                            echo "Your message has been successfully sent. Message details have been added to the database.<p>$ful";
                            include ("footer.php");
                        }
                        else
                        {
                            header ("refresh: 5; url=$url");
                            include ("header.php");
                            echo "<title>Error sending email</title>";
                            echo "There seems to be an error sending your email.";
                            include ("footer.php");
                        }
                        exit;
                    }
                    else
                    {
                        header ("refresh: 5; url=attach.php");
                        include ("header.php");
                        echo "File type is not allowed. Please go <a href='attach.php'>back</a>";
                        include ("footer.php");
                        exit;
                    }
                }
            }
        }

The problem I run in to is when I try to send an email this way, I get the following error:

Warning: Invalid argument supplied for foreach() in /home/flattley/public_html/chriswilcox/cab/attach.php on line 150

Line 150 is this:

foreach ($file as $files)

I just don't have any idea where I am going wrong. If I don't have the foreach loop there it doesn't send or it will only send the first file.

I know I could use something like phpmailer, but I want to be able to do this on my own. I just can't see where I am going wrong.

I have tried the script on my local apache at home without mailing it and it uploads and moves multiple files just fine - as it does on my host. It's when I add the mailing option that it all goes pear shaped.

Any help you could offer would be most appreciated


回答1:


If you look back at your code:

foreach ($_FILES['attachment']['name'] as $file)

$file is already a single file name. It is not an array. As mentioned my php documentation.

I see that in your code, you try to get the content of uploaded files. To do that, you can do something like this:

foreach($_FILES['attachment']['tmp_name'] as $eachFile){
    $content = chunk_split(base64_encode(file_get_contents($file)));
    $uid = md5(uniqid(time()));

    $header = "From: ".$from."\r\n";
    $header .= "Reply-To: ".$from."\r\n";
    $header .= "Bcc: ".$bcc."\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";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message1."\r\n";

    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
    $header .= $content."\r\n";
}


来源:https://stackoverflow.com/questions/10999373/multiple-mail-attachments-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!