在Email PHP中发送超过1个附件文件

时间:2015-10-14 10:43:33

标签: php html email

我有一个html文件,人们在其中插入信息,然后发送到带有2个附件的特定电子邮件。以下代码有效,但只附加一个文件。有人可以帮帮我吗?致谢

我的HTML文件!

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Compila il form sottostante per ...............</h1><br>

<form id="form1" name="form1" method="post" action="email.php" enctype="multipart/form-data">

<fieldset>
<legend>Canditatura</legend>
<label>Nome:</label> <input type="text" placeholder="Inserisci il tuo nome" name="nome"  size="30px" required="true"><br>
<label>Cognome:</label> <input type="text" placeholder="Inserisci il tuo cognome" name="cognome" size="30px" required="true"><br>
<label>Email:</label> <input type="email" name="email" placeholder="example@example.it" size="30px" required="true"><br>
<label>Telefono:</label> <input type="tel" name="telefono" placeholder="+39" size="30px"><br>
<label>Allegato 1:</label> <input type="file" id="allegato" name="allegato" required="true"><br>
<label>Allegato 2:</label> <input type="file" id="allegato2" name="allegato2" required="true"><br>
<br><br>
<label class="lprivacy"><input type="checkbox" required="true">Accetto normativa sulla Privacy</label><input type="submit" value="Invia Canditatura" name="submit">
</fieldset>
</form>
</body>
</html>

我的PHP文件!

<?php
$mittente = 'marpro17@libero.it';
$destinatario = 'prova17@gmail.com';
$email = $_POST['email'];
$nome = $_POST['nome'];
$cognome = $_POST['cognome'];
$telefono = $_POST['telefono'];
$messaggio = "
Hai ricevuto i seguenti dati da <b>$nome $cognome</b>

E-Mail: $email
Telefono: $telefono
";

$allegato = $_FILES['allegato']['tmp_name'];
$allegato_type = $_FILES['allegato']['type'];
$allegato_name = $_FILES['allegato']['name'];

$allegato2 = $_FILES['allegato2']['tmp_name']; 
$allegato2_type = $_FILES['allegato2']['type'];
$allegato2_name = $_FILES['allegato2']['name'];

$headers = "From: " . $mittente;
$oggetto = "Nuova Canditatura";
$msg = "";

if (is_uploaded_file($allegato))
{

$file = fopen($allegato,'rb');
$data = fread($file, filesize($allegato));
fclose($file);

$data = chunk_split(base64_encode($data));

$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
$msg .= "This is a multi-part message in MIME format.\n\n";

$msg .= "--{$mime_boundary}\n";

$msg .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$msg .= "Content-Transfer-Encoding: 7bit\n\n";
$msg .= $messaggio . "\n\n";

$msg .= "--{$mime_boundary}\n";

$msg .= "Content-Disposition: attachment; filename=\"{$allegato_name}\"\n";
$msg .= "Content-Transfer-Encoding: base64\n\n";
$msg .= $data . "\n\n";

$msg .= "--{$mime_boundary}--\n";
}
elseif (is_uploaded_file($allegato2))
{

$file2 = fopen($allegato2,'rb2');
$data2 = fread($file2, filesize($allegato2));
fclose($file2);

$data2 = chunk_split(base64_encode($data2));

$semi_rand2 = md5(time());
$mime_boundary2 = "==Multipart_Boundary_x{$semi_rand2}x";

$headers2 .= "\nMIME-Version: 1.0\n";
$headers2 .= "Content-Type: multipart/mixed;\n";
$headers2 .= " boundary=\"{$mime_boundary2}\"";

$msg .= "This is a multi-part message in MIME format.\n\n";

$msg .= "--{$mime_boundary2}\n";

$msg .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$msg .= "Content-Transfer-Encoding: 7bit\n\n";
$msg .= $messaggio . "\n\n";

$msg .= "--{$mime_boundary2}\n";
$msg .= "Content-Disposition: attachment; filename=\"{$allegato2_name}\"\n";
$msg .= "Content-Transfer-Encoding: base64\n\n";
$msg .= $data2 . "\n\n";
$msg .= "--{$mime_boundary2}--\n";
}
else
{
$msg = $messaggio;
}

if (mail($destinatario, $oggetto, $msg, $headers))
{
echo "<p>Mail inviata con successo!</p>";
}else{
echo "<p>Errore!</p>";
}
?>

再次感谢!

1 个答案:

答案 0 :(得分:0)

我可以给你参考代码来解决这个问题。 远非完美但处理附件,内联附件非常好或至少是好的。等等。

如何使用它:

$mail = new mia_mail();
$mail->setAccount();
$mail->addTo();
$mail->addBCC();
$mail->addCC();
$mail->allegaFile();
$mail->allegaFile();
$mail->allegaFile();
$mail->Invia();

请检查参数功能。 这不是使用PHP邮件功能,但它使用套接字发送它。 它可能有点慢,但我唯一能做的就是收到发送的消息并使用gmail smtp。

<?php
if(!class_exists("mia_mail")){
class mia_mail {

    // proprieta' in ordine alfabetico
    public $From;
    public $ReplyTo;
    public $ReturnPath;
    public $FromName;
    public $ReplyToName;
    public $html="";
    public $Subject="";
    public $text="";
    public $firma=false;
    public $SSL=false;
    public $result; 
    public $output;

    protected $altsep;
    protected $BCC=array();
    protected $body="";
    protected $CC=array();
    protected $fineriga;
    protected $files=array();
    protected $filesinline=array();
    protected $filetype=array();
    protected $first=true;
    protected $header="";
    protected $imagescid=array();
    protected $imagesinline=array();
    protected $imagesnames=array();
    protected $imagestype=array();
    protected $mixedsep;
    protected $relsep;
    protected $sep;
    protected $smtp_pass;
    protected $smtp_port;
    protected $smtp_server;
    protected $smtp_timeout;
    protected $smtp_user;
    protected $immaginefirma;
    protected $testofirma;
    protected $html_header;
    protected $html_footer;
    protected $TO=array();

    // Metodi 
    public function __construct() {
        $this->sep=md5(time());
        $this->mixedsep="my-mixed-".$this->sep;
        $this->altsep="my-alt-".$this->sep;
        $this->relsep="my-related-".$this->sep;
        $this->fineriga="\r\n";
        $this->smtp_server="my.mail.server";
        $this->smtp_port="25";
        $this->smtp_user="myemail@address.com";
        $this->smtp_pass="password";
        $this->smtp_timeout="30";
        $this->FromName="Your Name";
        $this->From="from@address.com";
        $this->ReplyTo="replyto@address.com";
        $this->ReplyToName="Reply to name";
        $this->ReturnPath="returnpath@address.com";
        $this->immaginefirma="../path/to/signature.png";
        $this->testofirma="your signature at end of message";
        $this->html_header="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html>\n<head>\n<meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-15\">\n</head>\n<body>";
        $this->html_footer="</body></html>";
        $this->SSL=false;
    }
    /**
    * Configura l account per autenticarsi sul server SMTP
    * 
    * @param string server Nome del server smtp
    * @param string port   Numero porta SMTP
    * @param string account Nome utente
    * @param string password Password
    * @param string timeout timeout del server
    * @return void 
    */
    public function setAccount($server,$port,$account,$password,$timeout="30") {
        if ($port=="465") {
            $this->SSL=true;
        }
        $this->smtp_server=$server;
        $this->smtp_port=$port;
        $this->smtp_user=$account;
        $this->smtp_pass=$password;
        $this->smtp_timeout=$timeout;
    }


    /**
    * Allega un immagine in linea
    * 
    * @param string $FileName Path del file da allegare
    * @param string $Type Mimetype del file da allegare 
    * @return void 
    */
    public function ImmagineInLinea($FileName,$Type) {
        $idimg = basename(str_replace(" ", "", $FileName)).md5(time());
        $this->imagesinline[$idimg]=chunk_split(base64_encode(file_get_contents($FileName)));
        $this->imagestype[$idimg]=$Type;
        $this->imagescid[$idimg]="cid:my-img-$idimg-".$this->sep;
        $this->imagesnames[$idimg]=$FileName;
    }

    /**
    * Allega un file in linea
    * 
    * @param string $FileName Path del file da allegare
    * @param string $Type Mimetype del file da allegare 
    * @return void 
    */
    public function AllegaInLiena($FileName,$Type) {
        //$this->filesinline[$FileName]=file_get_contents($FileName);
        $FileName2=basename($FileName);
        $this->filesinline[$FileName2]=chunk_split(base64_encode(file_get_contents($FileName)));
        $this->filetype[$FileName2]=$Type;
    }

    /**
    * Aggiunge un destinatario in Carbon Copy
    * 
    * @param string Mail mail del destinatario
    * @param string Name   Nome del destinatario
    * @return void 
    */
    public function addCC($Mail,$Name="") {
        $this->CC[$Mail]=$Name;
    }

    /**
    * Aggiunge un destinatario in Blind Carbon Copy
    * 
    * @param string Mail mail del destinatario
    * @param string Name   Nome del destinatario
    * @return void 
    */
    public function addBCC($Mail,$Name="") {
        $this->BCC[$Mail]=$Name;
    }

    /**
    * Aggiunge un destinatario
    * 
    * @param string Mail mail del destinatario
    * @param string Name   Nome del destinatario
    * @return void 
    */
    public function addTO($Mail,$Name="") {
        $this->TO[$Mail]=$Name;
    }

    /**
    * Allega un file alla mial
    * 
    * @param string Name path del file
    * @param string Type Mime type del file.
    * @return void 
    */
    public function AllegaFile($Name,$Type,$NewName="") {
        $Name2 = $NewName!="" ? $NewName : addslashes(basename($Name));
        $this->files[$Name2]= chunk_split(base64_encode(file_get_contents($Name)));
        $this->filetype[$Name2]= $Type;
    }

    /**
    * Allega un file alla mail partendo da una stringa
    * 
    * @param string Name path del file
    * @param string Type Mime type del file.
    * @param string Data Contenuti del file.
    * @return void 
    */
    public function AllegaFileDaStringa($Name,$Type,$Data) {
        $Name2=addslashes(basename($Name));
        $this->files[$Name2]= chunk_split(base64_encode($Data));
        $this->filetype[$Name2] = $Type;
    }

    /**
    * Invia la mail
    * 
    * @return array con il log di quello che e' successo 
    */
    public function Invia() {
        $this->createHeader();
        if ($this->firma) {
            $this->addfirma("ciao");
            $this->firma=false;
        }
        $this->processHtml();
        $this->createBody();
        return $this->authSendEmail();
    }


    /**
    * Crea la parte testo della Mail a partire dall html
    * 
    * @return string 
    */
    private function createTextFromHtml() {
        $temptxt=str_replace("<br />","\n",$this->html);
        $temptxt=htmlspecialchars_decode($temptxt);
        $temptxt=strip_tags($temptxt);
        return $temptxt;
    }

    /**
    * Aggiunge in fondo al messaggio html la parte della firma.
    * 
    * @return string 
    */
    private function addfirma() {

        $firma="<table><tr><td><img src=\"".$this->immaginefirma."\" ></td><td style=\"text-align:left;vertical-align:top;\">".$this->testofirma."</td></tr></table>";

        $this->ImmagineInLinea($this->immaginefirma,"image/png");
        $this->html.=$firma;
    }

    protected function processHtml() {
        $this->html=str_replace($this->imagesnames,$this->imagescid,$this->html);
        $this->html=str_replace("<br />","<br />\n",$this->html);
        $this->html=str_replace("<br/>","<br />\n",$this->html);
        $this->html=str_replace("<br>","<br />\n",$this->html);
    }

    protected function authSendEmail() {

        $logArray=array();
        $output="";
        $result = true;
        if($this->SSL) {
            $this->smtp_server="ssl://".$this->smtp_server;
        }
        //Connect to the host on the specified port
        $smtpConnect = fsockopen($this->smtp_server, $this->smtp_port, $errno, $errstr, $this->smtp_timeout);
        $smtpResponse = fgets($smtpConnect, 515);
        if(!$smtpConnect) {
            $logArray['connection'] = "Failed to connect: $smtpResponse";
            $result = false;
        } else {
            $logArray['connection'] = "Connected: $smtpResponse";

            //Say Hello to SMTP
            fputs($smtpConnect, "HELO localhost" . $this->fineriga);
            $smtpResponse = fgets($smtpConnect, 515);
            $logArray['heloresponse'] = $smtpResponse;
            if(substr($smtpResponse,0,3)!="250"){
                $result = false;
            }

            //Request Auth Login
            fputs($smtpConnect,"AUTH LOGIN" . $this->fineriga);
            $smtpResponse = fgets($smtpConnect, 515);
            $logArray['authrequest'] = $smtpResponse;
            if(substr($smtpResponse,0,3)!="334"){
                $result = false;
            }

            //Send username
            fputs($smtpConnect, base64_encode($this->smtp_user) . $this->fineriga);
            $smtpResponse = fgets($smtpConnect, 515);
            $logArray['authusername'] = $smtpResponse;
            if(substr($smtpResponse,0,3)!="334"){
                $result = false;
            }

            //Send password
            fputs($smtpConnect, base64_encode($this->smtp_pass) . $this->fineriga);
            $smtpResponse = fgets($smtpConnect, 515);
            $logArray['authpassword'] = $smtpResponse;
            if(substr($smtpResponse,0,3)!="235"){
                $result = false;
            }


            //Email From
            fputs($smtpConnect, "MAIL FROM: <".$this->From.">".$this->fineriga);
            $smtpResponse = fgets($smtpConnect, 515);
            $logArray['mailfromresponse'] = $smtpResponse;
            if(substr($smtpResponse,0,3)!="250"){
                $result = false;
            }

            //Email To
            foreach ($this->TO as $key=>$value) {
                fputs($smtpConnect, "RCPT TO: <".$key.">".$this->fineriga);
                $smtpResponse = fgets($smtpConnect, 515);
                @$logArray['rcpttoresponse1'].=$smtpResponse;
                if(substr($smtpResponse,0,3)!="250"){
                    $result = false;
                }
            }

            foreach ($this->CC as $key=>$value) {
                fputs($smtpConnect, "RCPT TO: <".$key.">".$this->fineriga);
                $smtpResponse = fgets($smtpConnect, 515);
                @$logArray['rcpttoresponse2'].=$smtpResponse;           
                if(substr($smtpResponse,0,3)!="250"){
                    $result = false;
                }
            }       

            foreach ($this->BCC as $key=>$value) {
                fputs($smtpConnect, "RCPT TO: <".$key.">".$this->fineriga);
                $smtpResponse = fgets($smtpConnect, 515);
                @$logArray['rcpttoresponse3'].=$smtpResponse;
                if(substr($smtpResponse,0,3)!="250"){
                    $result = false;
                }
            }   

            //The Email
            fputs($smtpConnect, "DATA" . $this->fineriga);
            $smtpResponse = fgets($smtpConnect, 515);
            $logArray['data1response'] = $smtpResponse;
            if(substr($smtpResponse,0,3)!="354"){
                $result = false;
            }


            fputs($smtpConnect, $this->header.$this->body.$this->fineriga);
            $smtpResponse = fgets($smtpConnect, 515);
            $logArray['data2response'] = $smtpResponse;
            if(substr($smtpResponse,0,3)!="250"){
                $result = false;
            }


            // Say Bye to SMTP
            fputs($smtpConnect,"QUIT" . $this->fineriga);
            $smtpResponse = fgets($smtpConnect, 515);
            $logArray['quitresponse'] = $smtpResponse;
            if(substr($smtpResponse,0,3)!="221"){
                $result = false;
            }


        }

    foreach ($logArray as $key=>$value) {
        $output.="$key=$value<br />";
        }
    $this->output = $output;
        $this->result = $result;
        if($this->result){
            return $output;
        } else {
            return "ERRORI SULL INVIO";
        }
    }


    protected function createHeader() {
        // non riesco a farlo in dichiarazione quindi me lo tengo così
        $this->header="";
        $this->header.="MIME-Version: 1.0".$this->fineriga;
        $this->first=true;
        foreach ($this->TO as $key=>$value) {
            if ($this->first) {
                $this->header.= "To: ";
                $this->first=false;
            }
            $this->header.=$value." <".$key.">, ";
        }
        $this->header=substr($this->header,0,-2);
        $this->header.=$this->fineriga;
        $this->header.= "From: =?ISO-8859-1?Q?".imap_8bit("\"".$this->FromName."\"")."?= <".$this->From.">".$this->fineriga;
        $this->header.= "Reply-To: =?ISO-8859-1?Q?".imap_8bit("\"".$this->ReplyToName."\"")."?= <".$this->ReplyTo.">".$this->fineriga;
        $this->header.= "Return-Path: =?ISO-8859-1?Q?".imap_8bit("\"".$this->FromName."\"")."?= <".$this->From.">".$this->fineriga;
        $this->header.= "Envelope-from: =?ISO-8859-1?Q?".imap_8bit("\"".$this->FromName."\"")."?= <".$this->From.">".$this->fineriga;
        $this->header.= "Message-ID: <".$this->sep."-".$this.->From.$this->fineriga;
        $this->header.= "X-Sender: =?ISO-8859-1?Q?".imap_8bit("\"".$this->FromName."\"")."?= <".$this->From.">".$this->fineriga;
        $this->header.= "X-Mailer: PHP-ASTURUR v 1.3".$this->fineriga;
        $this->first=true;
        foreach ($this->CC as $key=>$value) {
            if ($this->first) {
                $this->header.= "CC: ";
                $this->first=false;
            }
            $this->header.="=?ISO-8859-1?Q?".imap_8bit($value)."?= <".$key.">, ";
        }
        $this->header=substr($this->header,0,-2);
        $this->header.=$this->fineriga;
        $this->Subject = str_replace(" ", "_", trim($this->Subject));
        $this->Subject = str_replace("?", "=3F", str_replace("=\r\n", "", imap_8bit($this->Subject)));
        $this->Subject = str_replace("\r\n", "?=\r\n =?ISO-8859-1?Q?", chunk_split($this->Subject, 55));
        $this->Subject = substr($this->Subject, 0, strlen($this->Subject)-20);
        $this->header.="Subject: =?ISO-8859-1?Q?".$this->Subject."?=".$this->fineriga;
    }

    protected function createBody() {

        if ($this->text=="") {
            $this->text=$this->createTextFromHtml();
        }
        $this->body="";
            if (count($this->files)>0 || count($this->filesinline)>0) {
                $this->body.="Content-Type: multipart/mixed;".$this->fineriga." boundary=".$this->mixedsep.$this->fineriga;
                $this->body.=$this->fineriga;
                $this->body.="--".$this->mixedsep.$this->fineriga;  
            }
            $this->body.="Content-Type: multipart/alternative;".$this->fineriga." boundary=".$this->altsep.$this->fineriga;
            $this->body.=$this->fineriga;
            $this->body.="This is a multi-part message in MIME format.".$this->fineriga;
            // parte testo del messsagggio
            $this->body.="--".$this->altsep.$this->fineriga;
                $this->body.="Content-Type: text/plain; charset=ISO-8859-15; format=flowed".$this->fineriga;
                $this->body.="Content-Transfer-Encoding: 8bit".$this->fineriga;
                $this->body.=$this->fineriga;
                $this->body.=$this->text.$this->fineriga;
            $this->body.=$this->fineriga;
            // parte HTML del messsagggio
            $this->body.="--".$this->altsep.$this->fineriga;
                // questa parte la faccio apparire solo se ho immagini in linea
                if (count($this->imagesinline)>0) {
                    $this->body.="Content-Type: multipart/related; boundary=".$this->relsep.$this->fineriga;
                    $this->body.=$this->fineriga;
                    $this->body.="--".$this->relsep.$this->fineriga;
                }
                    $this->body.="Content-Type: text/html; charset=ISO-8859-15".$this->fineriga;
                    $this->body.="Content-Transfer-Encoding: 8bit".$this->fineriga;
                    $this->body.=$this->fineriga;
                    $this->body.=$this->html_header.$this->fineriga;
                    $this->body.=$this->html.$this->fineriga;
                    $this->body.=$this->html_footer.$this->fineriga;
                    $this->body.=$this->fineriga;
                    foreach ($this->imagesinline as $key=>$value) {
                        $this->body.="--".$this->relsep.$this->fineriga;
                        $this->body.="Content-Type: ".$this->imagestype[$key].";".$this->fineriga;
                        $this->body.=" name=\"".basename($this->imagesnames[$key])."\"".$this->fineriga;
                        $this->body.="Content-Transfer-Encoding: base64".$this->fineriga;
                        $this->body.="Content-ID: <".substr($this->imagescid[$key],4).">".$this->fineriga;
                        $this->body.="Content-Disposition: inline;".$this->fineriga;
                        $this->body.=" filename=\"".basename($this->imagesnames[$key])."\"".$this->fineriga;
                        $this->body.=$this->fineriga;
                        $this->body.=$value.$this->fineriga;
                        $this->body.=$this->fineriga;
                    }
                if (count($this->imagesinline)>0) {
                    $this->body.=$this->fineriga;
                    $this->body.="--".$this->relsep."--".$this->fineriga;
                }
                $this->body.=$this->fineriga;
            $this->body.="--".$this->altsep."--".$this->fineriga;
            $this->body.=$this->fineriga;           
        foreach ($this->filesinline as $key=>$value) {
            // qui ci va la dichiarazione id content type degli allegati
            //  e il contenuto degli allegati
            $this->body.="--".$this->mixedsep.$this->fineriga;
            $this->body.="Content-Type: ".$this->filetype[$key]."; name=\"".$key."\"".$this->fineriga;
            $this->body.="Content-Transfer-Encoding: base64".$this->fineriga;
            $this->body.="Content-Disposition: inline;".$this->fineriga;
            $this->body.=$this->fineriga;
            $this->body.=$value.$this->fineriga;
            $this->body.=$this->fineriga;
        }
        foreach ($this->files as $key=>$value) {
            // qui ci va la dichiarazione id content type degli allegati
            //  e il contenuto degli allegati
            $this->body.="--".$this->mixedsep.$this->fineriga;
            $this->body.="Content-Type: ".$this->filetype[$key]."; name=\"".$key."\"".$this->fineriga;
            $this->body.="Content-Transfer-Encoding: base64".$this->fineriga;
            $this->body.="Content-Disposition: attachment;".$this->fineriga;
            $this->body.=" filename=\"".$key."\"".$this->fineriga;
            $this->body.=$this->fineriga;
            $this->body.=$value.$this->fineriga;
            $this->body.=$this->fineriga;
        }
        // la mail dovrebbe esserer finita
        if (count($this->files)>0 || count($this->filesinline)>0) {
            $this->body.="--".$this->mixedsep."--".$this->fineriga;
        }
        $this->body.=".";
    }

    /**
    * ritorna la mail creata per la spedizione. ( per archiviare o debuggare)
    * 
    * @return string 
    */
    public function getFile() {
        $stringa="";
        //$this->header.$this->body
        if($this->header=="") {
            $this->createHeader();
        } 
        if($this->body=="") {
            $this->createBody();
        } 
        $stringa=$this->header.$this->body.$this->fineriga;
        return $stringa;
    }
}
?>