PHP: envío de correos electrónicos usando PHP

PHP debe estar configurado correctamente en el php.iniarchivo con los detalles de cómo su sistema envía el correo electrónico. Abra el archivo php.ini disponible en/etc/ directorio y busque la sección titulada [mail function].

Los usuarios de Windows deben asegurarse de que se proporcionen dos directivas. El primero se llama SMTP y define la dirección de su servidor de correo electrónico. El segundo se llama sendmail_from, que define su propia dirección de correo electrónico.

La configuración para Windows debería verse así:

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

; For win32 only
sendmail_from = [email protected]

Los usuarios de Linux simplemente necesitan que PHP sepa la ubicación de su sendmailsolicitud. La ruta y los conmutadores deseados deben especificarse en la directiva sendmail_path.

La configuración para Linux debería verse así:

[mail function]
; For Win32 only.
SMTP = 

; For win32 only
sendmail_from = 

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

Ahora estás listo para empezar.

Envío de correo electrónico de texto sin formato

PHP hace uso de mail()función para enviar un correo electrónico. Esta función requiere tres argumentos obligatorios que especifican la dirección de correo electrónico del destinatario, el asunto del mensaje y el mensaje real, además, hay otros dos parámetros opcionales.

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

Aquí está la descripción de cada parámetro.

No Señor Descripción de parámetros
1

to

Necesario. Especifica el destinatario / destinatarios del correo electrónico

2

subject

Necesario. Especifica el asunto del correo electrónico. Este parámetro no puede contener caracteres de nueva línea

3

message

Necesario. Define el mensaje a enviar. Cada línea debe estar separada con un LF (\ n). Las líneas no deben exceder los 70 caracteres

4

headers

Opcional. Especifica encabezados adicionales, como De, Cc y Cco. Los encabezados adicionales deben separarse con un CRLF (\ r \ n)

5

parameters

Opcional. Especifica un parámetro adicional al programa de envío de correo.

Tan pronto como se llame a la función de correo, PHP intentará enviar el correo electrónico y devolverá verdadero si tiene éxito o falso si falla.

Se pueden especificar varios destinatarios como primer argumento de la función mail () en una lista separada por comas.

Envío de correo electrónico HTML

Cuando envía un mensaje de texto usando PHP, todo el contenido se tratará como texto simple. Incluso si incluye etiquetas HTML en un mensaje de texto, se mostrará como texto simple y las etiquetas HTML no se formatearán de acuerdo con la sintaxis HTML. Pero PHP ofrece la opción de enviar un mensaje HTML como mensaje HTML real.

Al enviar un mensaje de correo electrónico, puede especificar una versión de Mime, el tipo de contenido y el juego de caracteres para enviar un correo electrónico HTML.

Ejemplo

El siguiente ejemplo enviará un mensaje de correo electrónico HTML a [email protected] copiándolo a [email protected] Puede codificar este programa de tal manera que reciba todo el contenido del usuario y luego envíe un correo electrónico.

<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>

Envío de archivos adjuntos con correo electrónico

Para enviar un correo electrónico con contenido mixto, es necesario configurar Content-type encabezado a multipart/mixed. Luego, las secciones de texto y adjuntos se pueden especificar dentroboundaries.

Un límite se inicia con dos guiones seguidos de un número único que no puede aparecer en la parte del mensaje del correo electrónico. Una función PHPmd5()se utiliza para crear un número hexadecimal de 32 dígitos para crear un número único. Un límite final que indique la sección final del correo electrónico también debe terminar con dos guiones.

<?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>