Foros del Web » Programando para Internet » PHP »

Enviar mail con archivo adjunto

Estas en el tema de Enviar mail con archivo adjunto en el foro de PHP en Foros del Web. Hola, tengo un formulario para enviar datos por mail, ahora queria agregarle que se pueda adjuntar un archivo en el mismo formulario. Soy novato en ...
  #1 (permalink)  
Antiguo 28/05/2012, 17:33
 
Fecha de Ingreso: julio-2009
Mensajes: 28
Antigüedad: 14 años, 9 meses
Puntos: 0
Enviar mail con archivo adjunto

Hola, tengo un formulario para enviar datos por mail, ahora queria agregarle que se pueda adjuntar un archivo en el mismo formulario. Soy novato en php, solo busco y voy modificando y probando, logreo armar el formulario y modifique el codigo, el mail me llega perfecto , con el nombre del archivo que se adjunto. Pero el archivo no llega, incluso el mail me aparece marcado con el clip , como que trajera un adjunto peor no se que me puede falta o como corregir esto, por favor necesitaria ayuda.

gracias
  #2 (permalink)  
Antiguo 28/05/2012, 19:29
marcofbb
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Enviar mail con archivo adjunto

Gabriel Omar,
Me gusta que este interesado en esto del PHP pero el foro esta abierto a todo aquel que quiera aprender y estudiar para hacerlo. El tema de mail con archivos adjuntos en forosdelweb esta mas que hablado y si buscaras en Google también. No estoy acusando de que no hayas buscado, por ahi solamente buscaste con términos incorrectos.

Ahora mismo yo busque para encontrar alguna respuesta coherente con tu pregunta, "archivo adjunto PHPmailer"

Algunos resultados interesantes fueron:

http://www.ramdeit.com/hosting/manua...-php-phpmailer
http://blog.unijimpe.net/introduccion-a-phpmailer/
http://blog.unijimpe.net/enviar-email-con-adjuntos/

También con los términos "Archivo adjunto mail php" encontré artículos sumamente interesantes

http://www.original-design.es/tutori...juntos_php.php
http://www.comalis.com/ayuda/formula...junto-mail.php
http://www.diegodicamillo.com.ar/blo...n-mail-de-php/

Usted habla de que ya tiene el código y que le llega el mail con su respectivo icono de archivo adjunto, estaría bueno que dejes parte del código para saber en que le estas errando.

PD: No quiero que te ofendas solo es una critica constructiva, creo que la mayoría de los usuarios leyeron este post y no lo respondieron por lo que aclare arriba.
  #3 (permalink)  
Antiguo 30/05/2012, 15:56
 
Fecha de Ingreso: julio-2009
Mensajes: 28
Antigüedad: 14 años, 9 meses
Puntos: 0
Respuesta: Enviar mail con archivo adjunto

Hola..muchisimas gracias marco, no se que paso pero el mismo dia que me respondiste ta habia escrito para agradecerte, inclusive te habia mandado el codigo pero ahora veo que no esta mi respuesta, no se qeu paso. Te paso el codigo por las dudas si queres pegarle una mirada, ahora voy a revisar los links que me mandaste. Te juto que busque en google pero las ayudas que encontre eran todas subiendo el archivo al servidor y reenviando.. y otras me daba algun tipo de error que dado mi ignorancia en el tema no podia solucionar...espero poder resolverlo....

otra vez mil gracias y aca va el codigo, hay partes que ni idea lo que hacen, solo usaba porque me daba resultado para lo que queria hasta ese momento...
  #4 (permalink)  
Antiguo 30/05/2012, 15:57
 
Fecha de Ingreso: julio-2009
Mensajes: 28
Antigüedad: 14 años, 9 meses
Puntos: 0
Respuesta: Enviar mail con archivo adjunto

Código PHP:
# Validacion de Datos
function ValidarDatos($campo){
    
//Array con las posibles cabeceras a utilizar por un spammer
    
$badHeads = array("Content-Type:",
    
"MIME-Version:",
    
"Content-Transfer-Encoding:",
    
"Return-path:",
    
"Subject:",
    
"From:",
    
"Envelope-to:",
    
"To:",
    
"bcc:",
    
"cc:");
        foreach(
$badHeads as $valor){
        if(
strpos(strtolower($campo), strtolower($valor)) !== false){
            return 
false;
        }
    }
        return 
true;
}
function 
ReemplazarHeader($campo){
    
//Array con las posibles cabeceras a utilizar por un spammer
    
$badHeads = array(
    array(
0=>"[ \t]{0,3}Content-Type:[ \t]{1}",1=>" '*Content-Type:*' "),
    array(
0=>"[ \t]{0,3}MIME-Version:[ \t]{1}",1=>" '*MIME-Version:*' "),
    array(
0=>"[ \t]{0,3}Content-Transfer-Encoding:[ \t]{1}",1=>" '*Content-Transfer-Encoding:*' "),
    array(
0=>"[ \t]{0,3}Return-path:[ \t]{1}",1=>" '*Return-path:*' "),
    array(
0=>"[ \t]{0,3}Subject:[ \t]{1}",1=>" '*Subject:*' "),
    array(
0=>"[ \t]{0,3}From:[ \t]{1}",1=>" '*From:*' "),
    array(
0=>"[ \t]{0,3}Envelope-to:[ \t]{1}",1=>" '*Envelope-to:*' "),
    array(
0=>"[ \t]{0,3}(T|t)o:[ \t]{1}",1=>" '*To:*' "),
    array(
0=>"[ \t]{0,3}bcc:[ \t]{1}",1=>" '*bcc:*' "),
    array(
0=>"[ \t]{0,3}cc:[ \t]{1}",1=>" '*cc:*' ")
    );
    foreach(
$badHeads as $a_badheader){
        
$campo eregi_replace($a_badheader[0], $a_badheader[1], $campo);
    }
    return 
$campo;
}
function 
CodificarQP ($str) {global $eol;
    
$encoded ArreglarEOL($str);
    if (
substr($encoded, -(strlen($eol))) != $eol)
    
$encoded .= $eol;
    
$encoded preg_replace('/([\000-\010\013\014\016-\037\075\177-\377])/e',
            
"'='.sprintf('%02X', ord('\\1'))"$encoded);
    
$encoded preg_replace("/([\011\040])".$eol."/e",
            
"'='.sprintf('%02X', ord('\\1')).'".$eol."'"$encoded);
    
$encoded AdaptarTexto($encoded74true);
        return 
$encoded;
}
function 
ArreglarEOL($str) {global $eol;
        
$str str_replace("\r\n""\n"$str);
    
$str str_replace("\r""\n"$str);
    
$str str_replace("\n"$eol$str);
    return 
$str;
}
function 
AdaptarTexto($message$length$qp_mode false) {
    global 
$eol;

        
$soft_break = ($qp_mode) ? sprintf(" =%s"$eol) : $eol;
        
$message ArreglarEOL($message);
        if (
substr($message, -1) == $eol)
            
$message substr($message0, -1);
        
$line explode($eol$message);
        
$message "";
        for (
$i=;$i count($line); $i++)
        {
$line_part explode(" "$line[$i]);
          
$buf "";
          for (
$e 0$e<count($line_part); $e++)
          { 
$word $line_part[$e];
              if (
$qp_mode and (strlen($word) > $length))
              {
                
$space_left $length strlen($buf) - 1;
                if (
$e != 0)
                { if (
$space_left 20)   {
                        
$len $space_left;
                        if (
substr($word$len 11) == "=")
                          
$len--;
                        elseif (
substr($word$len 21) == "=")
                          
$len -= 2;
                        
$part substr($word0$len);
                        
$word substr($word$len);
                        
$buf .= " " $part;
                        
$message .= $buf sprintf("=%s"$eol);
                    }
                    else
                    {
$message .= $buf $soft_break;}
                    
$buf "";
                }
                while (
strlen($word) > 0)
                {
                    
$len $length;
                    if (
substr($word$len 11) == "=")
                        
$len--;
                    elseif (
substr($word$len 21) == "=")
                        
$len -= 2;
                    
$part substr($word0$len);
                    
$word substr($word$len);
                    if (
strlen($word) > 0)
                        
$message .= $part sprintf("=%s"$eol);
                    else
                        
$buf $part;
                }
              }
              else
              {
                
$buf_o $buf;
                
$buf .= ($e == 0) ? $word : (" " $word); 

                if (
strlen($buf) > $length and $buf_o != "")
                {
                    
$message .= $buf_o $soft_break;
                    
$buf $word;
                }
              }
          }
          
$message .= $buf $eol;
        }
        return 
$message;
}
$s_mailer_type 'mail';

if (!
file_exists('E:/php5/PhpCommon/fzo.mail.php') && $s_mailer_type == 'smtp') {
    
$s_mailer_type 'mail';
}
if (
$s_mailer_type == 'smtp') {
    function 
_fzo_mail$s_to$s_subject$s_message$s_additional_headers='') {
        require_once(
"fzo.mail.php");
        global 
$eol;
        if (empty(
$eol)) {
            
$eol "\n";
        }
        
$mail = new SMTP("localhost",'','');

        
$s_from '[email protected]';

        if (empty(
$s_from) || $s_from == ('<!--%' 'email_from_address' '%-->')) {
            
$s_host $_SERVER["HTTP_HOST"];
            
$s_host ereg_replace("www\."""$s_host);
            
$s_from "no-reply@" $s_host;
        }
        
$s_header $mail->make_header(
                    
$s_from,
                    
$s_to,
                    
$s_subject,
                    
'3',
                    
''
                
''
                
);
        
$s_additional_headers trim($s_header) . $eol $s_additional_headers;

        
// Se envia el correo y se verifica el error
        
$error $mail->smtp_send($s_from$s_to$s_additional_headers$s_message'''');
            if (
$error == "0") {
            
//echo "E-mail enviado correctamente";
            
return true;
        }else {
//echo "Error al enviar email: " . $error . "\n";
            
return false;}
        }
}
# Is the OS Windows or Mac or Linux
if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
  
$eol="\r\n";
} elseif (
strtoupper(substr(PHP_OS,0,3)=='MAC')) {
  
$eol="\r";
} else {
  
$eol="\n";
}
$now date("YmdHis");

$s_mailer_enabled 'TRUE';

# To Email Address
$emailaddress="[email protected]";
$emailaddressfrom="[email protected]";
# Message Subject
$emailsubject="email de contacto desde el sitio www.litoralrrhh.com.ar ";
# Message Body
$body_txt_prefix_data="";
$body_txt_separator_data=": ";
$body_txt_sufix_data=$eol;

$body_txt_prefix="Datos del Formulario:".$eol;
$body_txt_data="";
$body_txt_sufix=$eol."www.litoralrrhh.com.ar";

$body_html_prefix_data 
        
"<tr>
            <td>"
;
$body_html_separator_data=": </td><td>";
$body_html_sufix_data="</td>
        </tr>
"
;
$body_html_prefix="<html>
<body>
    <table>
        <tr>
            <td colspan=\"2\">Datos del Formulario:</td>
        </tr>"
;
$body_html_data="";
$body_html_sufix="        <tr>
            <td colspan=\"2\"><br/>www.litoralrrhh.com.ar</td>
        </tr>
</table>
</body>
</html>"
;
# Get Data
foreach($_POST as $s_name => $s_value) {
    if (
strtolower($s_name) != 'submit') {
        
$s_name ucwords(str_replace("_"," ",$s_name));
        
$s_value stripslashes ($s_value);
        
$body_txt_data.=$body_txt_prefix_data.$s_name.$body_txt_separator_data.$s_value.$body_txt_sufix_data;
        
$body_html_data.=$body_html_prefix_data.$s_name.$body_html_separator_data.$s_value.$body_html_sufix_data;
    }
}
# Merge Data
$body_txt=$body_txt_prefix.$body_txt_data.$body_txt_sufix;
$body_html=$body_html_prefix.$body_html_data.$body_html_sufix;

$body_txt ReemplazarHeader($body_txt);
$body_html ReemplazarHeader($body_html);

# Common Headers
$headers .= 'From: '.$emailaddressfrom.$eol;
$headers .= 'Reply-To: '.$emailaddressfrom.$eol;
$headers .= 'Return-Path: '.$emailaddressfrom.$eol;    // these two to set reply address
$headers .= "X-Mailer: PHP v".phpversion().$eol;   // These two to help avoid spam-filters
# Boundry for marking the split & Multitype Headers
$mime_boundary=md5(time());
$headers .= 'MIME-Version: 1.0'.$eol;
# Setup for text OR html
$headers .= "Content-Type: multipart/alternative; boundary=\"".$mime_boundary."\"".$eol;
$headers .= "Message-ID: <".$now.".TheSystem@".$_SERVER['SERVER_NAME'].">".$eol;
$msg "";
# Text Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: quoted-printable".$eol.$eol;
$msg .= CodificarQP($body_txt).$eol;
# HTML Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: quoted-printable".$eol.$eol;
$msg .= CodificarQP("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">").$eol;
$msg .= CodificarQP($body_html).$eol.$eol;

# Setup for attachment
$msg .= "Content-Type: multipart/related".$eol;
# Attachment
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: application/msword; name=\"".$letter."\"".$eol;  // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
$msg .= "Content-Transfer-Encoding: base64".$eol;
$msg .= "Content-Disposition: attachment; filename=\"".$letter."\"".$eol.$eol// !! This line needs TWO end of lines !! IMPORTANT !!
$msg .= $f_contents.$eol.$eol;

# Finished
$msg .= "--".$mime_boundary."--".$eol.$eol;  // finish with two eol's for better security. see Injection.

//Ejemplo de llamadas a la funcion
if(ValidarDatos($emailaddress) && ValidarDatos($emailsubject/*&& ValidarDatos($body_txt) && ValidarDatos($body_html)*/){
    
# SEND THE EMAIL
    
if ($s_mailer_enabled == 'TRUE') {    if ($s_mailer_type=='smtp') {
            
$resp _fzo_mail($emailaddress$emailsubject$msg$headers);
        }
        else {
$resp mail($emailaddress$emailsubject$msg$headers);        }
    }else {    
$resp false;
    }
}
else {
$resp false;}
if(
$resp) {$s_location "fs_ok_form.html";}
else {
$s_location "fs_error_form.html";}
header("Location: ./$s_location"); 

Etiquetas: adjuntos, mail
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 03:19.