PHP - Invio di e-mail utilizzando PHP

PHP deve essere configurato correttamente nel file php.inifile con i dettagli di come il sistema invia la posta elettronica. Apri il file php.ini disponibile in/etc/ directory e trova la sezione intitolata [mail function].

Gli utenti Windows dovrebbero assicurarsi che vengano fornite due direttive. Il primo si chiama SMTP che definisce l'indirizzo del tuo server di posta elettronica. Il secondo si chiama sendmail_from che definisce il tuo indirizzo email.

La configurazione per Windows dovrebbe essere simile a questa:

[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net

; For win32 only
sendmail_from = [email protected]

Gli utenti Linux devono semplicemente far sapere a PHP la posizione del loro file sendmailapplicazione. Il percorso e tutte le opzioni desiderate dovrebbero essere specificate nella direttiva sendmail_path.

La configurazione per Linux dovrebbe assomigliare a questa:

[mail function]
; For Win32 only.
SMTP = 

; For win32 only
sendmail_from = 

; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i

Ora sei pronto per andare -

Invio di e-mail in testo semplice

PHP utilizza mail()funzione per inviare un'e-mail. Questa funzione richiede tre argomenti obbligatori che specificano l'indirizzo e-mail del destinatario, l'oggetto del messaggio e il messaggio effettivo inoltre ci sono altri due parametri opzionali.

mail( to, subject, message, headers, parameters );

Ecco la descrizione di ogni parametro.

Suor n Parametro e descrizione
1

to

Necessario. Specifica il destinatario / i destinatari dell'email

2

subject

Necessario. Specifica l'oggetto dell'email. Questo parametro non può contenere caratteri di nuova riga

3

message

Necessario. Definisce il messaggio da inviare. Ogni riga dovrebbe essere separata con un LF (\ n). Le righe non devono superare i 70 caratteri

4

headers

Opzionale. Specifica intestazioni aggiuntive, come From, Cc e Ccn. Le intestazioni aggiuntive dovrebbero essere separate con un CRLF (\ r \ n)

5

parameters

Opzionale. Specifica un parametro aggiuntivo per il programma di invio della posta

Non appena la funzione di posta viene chiamata, PHP tenterà di inviare l'email, quindi restituirà vero se ha successo o falso se non è riuscito.

È possibile specificare più destinatari come primo argomento della funzione mail () in un elenco separato da virgole.

Invio di email HTML

Quando invii un messaggio di testo utilizzando PHP, tutto il contenuto verrà trattato come testo semplice. Anche se includerai tag HTML in un messaggio di testo, verrà visualizzato come testo semplice e i tag HTML non verranno formattati secondo la sintassi HTML. Ma PHP fornisce l'opzione per inviare un messaggio HTML come messaggio HTML effettivo.

Durante l'invio di un messaggio di posta elettronica è possibile specificare una versione Mime, il tipo di contenuto e il set di caratteri per inviare un messaggio di posta elettronica HTML.

Esempio

L'esempio seguente invierà un messaggio di posta elettronica HTML a [email protected] copiandolo in [email protected] Puoi codificare questo programma in modo tale che riceva tutto il contenuto dall'utente e quindi dovrebbe inviare un'e-mail.

<html>
   
   <head>
      <title>Sending HTML email using PHP</title>
   </head>
   
   <body>
      
      <?php
         $to = "[email protected]";
         $subject = "This is subject";
         
         $message = "<b>This is HTML message.</b>";
         $message .= "<h1>This is headline.</h1>";
         
         $header = "From:[email protected] \r\n";
         $header .= "Cc:[email protected] \r\n";
         $header .= "MIME-Version: 1.0\r\n";
         $header .= "Content-type: text/html\r\n";
         
         $retval = mail ($to,$subject,$message,$header);
         
         if( $retval == true ) {
            echo "Message sent successfully...";
         }else {
            echo "Message could not be sent...";
         }
      ?>
      
   </body>
</html>

Invio di allegati con e-mail

Per inviare un'e-mail con contenuto misto è necessario impostare Content-type intestazione a multipart/mixed. Quindi è possibile specificare sezioni di testo e allegati all'internoboundaries.

Un confine inizia con due trattini seguiti da un numero univoco che non può apparire nella parte del messaggio dell'email. Una funzione PHPmd5()viene utilizzato per creare un numero esadecimale a 32 cifre per creare un numero univoco. Anche un confine finale che denota la sezione finale dell'email deve terminare con due trattini.

<?php
   // request variables // important
   $from = $_REQUEST["from"];
   $emaila = $_REQUEST["emaila"];
   $filea = $_REQUEST["filea"];
   
   if ($filea) {
      function mail_attachment ($from , $to, $subject, $message, $attachment){
         $fileatt = $attachment; // Path to the file
         $fileatt_type = "application/octet-stream"; // File Type 
         
         $start = strrpos($attachment, '/') == -1 ? 
            strrpos($attachment, '//') : strrpos($attachment, '/')+1;
				
         $fileatt_name = substr($attachment, $start, 
            strlen($attachment)); // Filename that will be used for the 
            file as the attachment 
         
         $email_from = $from; // Who the email is from
         $subject = "New Attachment Message";
         
         $email_subject =  $subject; // The Subject of the email 
         $email_txt = $message; // Message that the email has in it 
         $email_to = $to; // Who the email is to
         
         $headers = "From: ".$email_from;
         $file = fopen($fileatt,'rb'); 
         $data = fread($file,filesize($fileatt)); 
         fclose($file); 
         
         $msg_txt="\n\n You have recieved a new attachment message from $from";
         $semi_rand = md5(time()); 
         $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
         $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . "
            boundary=\"{$mime_boundary}\"";
         
         $email_txt .= $msg_txt;
			
         $email_message .= "This is a multi-part message in MIME format.\n\n" . 
            "--{$mime_boundary}\n" . "Content-Type:text/html; 
            charset = \"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . 
            $email_txt . "\n\n";
				
         $data = chunk_split(base64_encode($data));
         
         $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" .
            " name = \"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" . 
            //" filename = \"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: 
            base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n";
				
         $ok = mail($email_to, $email_subject, $email_message, $headers);
         
         if($ok) {
            echo "File Sent Successfully.";
            unlink($attachment); // delete a file after attachment sent.
         }else {
            die("Sorry but the email could not be sent. Please go back and try again!");
         }
      }
      move_uploaded_file($_FILES["filea"]["tmp_name"],
         'temp/'.basename($_FILES['filea']['name']));
			
      mail_attachment("$from", "[email protected]", 
         "subject", "message", ("temp/".$_FILES["filea"]["name"]));
   }
?>

<html>
   <head>
      
      <script language = "javascript" type = "text/javascript">
         function CheckData45() {
            with(document.filepost) {
               if(filea.value ! = "") {
                  document.getElementById('one').innerText = 
                     "Attaching File ... Please Wait";
               }
            }
         }
      </script>
      
   </head>
   <body>
      
      <table width = "100%" height = "100%" border = "0" 
         cellpadding = "0" cellspacing = "0">
         <tr>
            <td align = "center">
               <form name = "filepost" method = "post" 
                  action = "file.php" enctype = "multipart/form-data" id = "file">
                  
                  <table width = "300" border = "0" cellspacing = "0" 
                     cellpadding = "0">
							
                     <tr valign = "bottom">
                        <td height = "20">Your Name:</td>
                     </tr>
                     
                     <tr>
                        <td><input name = "from" type = "text" 
                           id = "from" size = "30"></td>
                     </tr>
                     
                     <tr valign = "bottom">
                        <td height = "20">Your Email Address:</td>
                     </tr>
                     
                     <tr>
                        <td class = "frmtxt2"><input name = "emaila"
                           type = "text" id = "emaila" size = "30"></td>
                     </tr>
                     
                     <tr>
                        <td height = "20" valign = "bottom">Attach File:</td>
                     </tr>
                     
                     <tr valign = "bottom">
                        <td valign = "bottom"><input name = "filea" 
                           type = "file" id = "filea" size = "16"></td>
                     </tr>
                     
                     <tr>
                        <td height = "40" valign = "middle"><input 
                           name = "Reset2" type = "reset" id = "Reset2" value = "Reset">
                        <input name = "Submit2" type = "submit" 
                           value = "Submit" onClick = "return CheckData45()"></td>
                     </tr>
                  </table>
                  
               </form>
               
               <center>
                  <table width = "400">
                     
                     <tr>
                        <td id = "one">
                        </td>
                     </tr>
                     
                  </table>
               </center>
               
            </td>
         </tr>
      </table>
      
   </body>
</html>