Foros del Web » Programando para Internet » PHP »

envio con PHPMailer adjuntos segun opcion

Estas en el tema de envio con PHPMailer adjuntos segun opcion en el foro de PHP en Foros del Web. Mi consulta es la siguiente, estoy utilizando PHPMailer smtp para el envio de mail a traves de un formulario. puedo enviar un archivo adjunto que ...
  #1 (permalink)  
Antiguo 08/12/2005, 12:21
Usuario no validado
 
Fecha de Ingreso: agosto-2004
Mensajes: 74
Antigüedad: 19 años, 7 meses
Puntos: 0
envio con PHPMailer adjuntos segun opcion

Mi consulta es la siguiente, estoy utilizando PHPMailer smtp para el envio de mail a traves de un formulario. puedo enviar un archivo adjunto que esta en una carpeta del servidor sin problema, incluyendo en el codigo php

Código PHP:
$mail->AddAttachment(documentos/archivo.pdf); 
lo que me gustaria hacer es que a traves del formulario, pudiera seleccionar con casillas de verificacion el archivo a adjuntar en cada envio y tambien poder enviar mas de uno si lo creyese conveniente.

la verdad es que no se como hacerlo, imagino que con

Código PHP:
if ($info1==ON)  {
     
$mail->AddAttachment(documentos/archivo.pdf);

pero no me funciona. alguien me puede ayudar?

mi formulario es el siguiente:
Código PHP:
<FORM ENCTYPE="multipart/form-data" METHOD="post" ACTION="<?=$PHP_SELF?>">
                <div align="center">
                    <p style="margin-top: 1px; margin-bottom: 1px">
                    <font color="#FF0000" face="Verdana" size="2"><b>.:Envío de 
                    Información</b></font></p>
                    <table border="0" height="241" bgcolor="#E6E6E6" id="table1" width="381" cellpadding="5">
                        <tr>
                            <td height="22" colspan="2" width="118">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">
                            Empresa</font></b></td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <font size="1" face="Verdana" color="#666666">
                            <input type="text" name="empresa" size="35" style="font-size: 8pt; font-family: Verdana"></font></td>
                        </tr>
                        <tr>
                            <td height="19" colspan="2">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">Envió 
                            Email a</font></b></td>
                            <td height="19" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <font color="#666666">
                            <input type="text" name="email1" size="35" style="font-size: 8pt; font-family: Verdana"></font></td>
                        </tr>
                        <tr>
                            <td height="21" colspan="2">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font face="Verdana" size="1" color="#666666">A la 
                            atención de ...</font></b></td>
                            <td height="21" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <input type="text" name="contacto" size="35" style="font-size: 8pt; font-family: Verdana"></td>
                        </tr>
                        <tr>
                            <td height="142" rowspan="6" width="89">
                            <p style="margin-top: 1px; margin-bottom: 1px">&nbsp;</td>
                            <td height="22" align="center" width="25">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <input type="checkbox" name="info1" value="ON"></td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">&nbsp;Información 
                            1</font></b></td>
                        </tr>
                        <tr>
                            <td height="22" align="center" width="25">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <font face="Verdana" size="1" color="#666666">
                            <input type="checkbox" name="info2" value="ON" style="font-weight: 700"></font></td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">&nbsp;Información 
                            2</font></b></td>
                        </tr>
                        <tr>
                            <td height="22" align="center" width="25">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <font face="Verdana" size="1" color="#666666">
                            <input type="checkbox" name="info3" value="ON" style="font-weight: 700"></font></td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">&nbsp;Información 
                            3</font></b></td>
                        </tr>
                        <tr>
                            <td height="22" align="center" width="25">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <font face="Verdana" size="1" color="#666666">
                            <input type="checkbox" name="info4" value="ON" style="font-weight: 700"></font></td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">&nbsp;Información 
                            4</font></b></td>
                        </tr>
                        <tr>
                            <td height="22" align="center" width="25">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <font face="Verdana" size="1" color="#666666">
                            <input type="checkbox" name="info5" value="ON" style="font-weight: 700"></font></td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">
                            &nbsp;Información 5 </font></b></td>
                        </tr>
                        <tr>
                            <td height="22" align="center" width="25">
                            <p style="margin-top: 1px; margin-bottom: 1px">&nbsp;</td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">&nbsp;</font></b></td>
                        </tr>
                    </table>
                </div>
                <p align="center" style="margin-top: 1px; margin-bottom: 1px">
                <input type="submit" value="Enviar" name="enviar">&nbsp;&nbsp;
                <input type="reset" value="Restablecer" name="borrar"></p>
            </form>
  #2 (permalink)  
Antiguo 08/12/2005, 12:35
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 2 meses
Puntos: 129
El valor de un "checkbox" de un formulario .. sólo pasa a tu script de proceso SI se selecciona .. si no se selecciona .. ni la variable que definas para ese checkbox existirá para PHP ..

Por ende . .basado en esa filosofía puedes hacer dos cosas:

Solución 1:

Como lo hacias .. pero es "ON" es una cadena (el valor que definistes en tu checkbox "value") .. Así que tendrá que ir entre comillas. Además usa los arrays superglobales: tu dato llegan por $_POST .. usalos!.

Código PHP:
if ($_POST['info1']=="ON")  { 
     
$mail->AddAttachment(documentos/archivo.pdf); 

Solución 2:

Basado en si existe o no la variable que defines nombre para el checkbox, sabiendo que si NO se selecciona .. no existirá .. El valor no me interesa para este caso, lo usamos como un "flag" (bandera, estado ..).

Código PHP:
if (isset($_POST['info1']))  { 
     
$mail->AddAttachment(documentos/archivo.pdf); 


Un saludo,
  #3 (permalink)  
Antiguo 08/12/2005, 13:19
Usuario no validado
 
Fecha de Ingreso: agosto-2004
Mensajes: 74
Antigüedad: 19 años, 7 meses
Puntos: 0
PHPMailer adjuntos segun opcion

Ahora de nuevo me envia el mail, pero no adjunta el archivo. envio el codigo completo para ver donde puedo tener el fallo

Gracias por tu atencion

Código PHP:
<?
   
//Es necesario que al menos halla una dirección de destino
   
$error="";

   if (
$enviar) {
      if ((!
$email1) && (!$email2)) {
    
$error.="Debe indicar al menos una dirección de destino";
      }
   }
    
   if (
$enviar && !$error) {

      
//creamos un array que estará formado por las direcciones de destino
      
if ($email1) {
    
$direcciones["direccion1"]=$email1;
      }
      if (
$email2) {
    
$direcciones["direccion2"]=$email2;
      }

      
//pasamos a enviar el correo

      // primero hay que incluir la clase phpmailer para poder instanciar 
      //un objeto de la misma
      
require "includes/class.phpmailer.php";

      
//instanciamos un objeto de la clase phpmailer al que llamamos 
      //por ejemplo mail
      
$mail = new phpmailer();

      
//Definimos las propiedades y llamamos a los métodos 
      //correspondientes del objeto mail

      //Con PluginDir le indicamos a la clase phpmailer donde se 
      //encuentra la clase smtp que como he comentado al principio de 
      //este ejemplo va a estar en el subdirectorio includes
      
$mail->PluginDir "includes/";

      
//Con la propiedad Mailer le indicamos que vamos a usar un 
      //servidor smtp                            
      
$mail->Mailer "smtp";

      
//Asignamos a Host el nombre de nuestro servidor smtp
      
$mail->Host "mail.dominio.com";
      
      
//Le indicamos que el servidor smtp requiere autenticación
      
$mail->SMTPAuth true;

      
//Le decimos cual es nuestro nombre de usuario y password
      
$mail->Username "[email protected]";
      
$mail->Password "xxxxxxxxxxxxx";
      
      
//Indicamos cual es nuestra dirección de correo y el nombre que 
      //queremos que vea el usuario que lee nuestro correo
      
$mail->From "[email protected]";

      
$mail->FromName "Mi nombre";

      
//Asignamos asunto y cuerpo del mensaje
      //El cuerpo del mensaje lo ponemos en formato html, haciendo 
      //que se vea en negrita
      
$mail->Subject "Informacion Solicitada a mi empresa";
      
$mail->Body "<b>Señores aqui tienen la informacion que nos han solicitado</b>";

      
//Definimos AltBody por si el destinatario del correo no admite 
      //email con formato html
      
$mail->AltBody ="Mensaje de prueba mandado con phpmailer en formato texto";

      
//el valor por defecto 10 de Timeout es un poco escaso dado que voy a usar 
      //una cuenta gratuita y voy a usar attachments, por tanto lo pongo a 120  
      
$mail->Timeout=20;

      
//Indicamos el fichero a adjuntar si el usuario seleccionó uno en el formulario
       
if ($_POST['info1']=="ON")  { 
     
$mail->AddAttachment(documentos/archivo.pdf); 

      
      
//Indicamos cuales son las direcciones de destino del correo y enviamos 
      //los mensajes
      
reset($direcciones);
      while (list(
$clave$valor)=each($direcciones)) {
    
$mail->AddAddress($valor);

    
//se envia el mensaje, si no ha habido problemas la variable $success 
    //tendra el valor true
    
$exito $mail->Send();

    
//Si el mensaje no ha podido ser enviado se realizaran 4 intentos mas 
    //como mucho para intentar enviar el mensaje, cada intento se hara 5 s
    //segundos despues del anterior, para ello se usa la funcion sleep
     
$intentos=1
       while((!
$exito)&&($intentos<5)&&($mail->ErrorInfo!="SMTP Error: Data not accepted")){
       
sleep(5);
            
//echo $mail->ErrorInfo;
            
$exito $mail->Send();
            
$intentos=$intentos+1;                
       }

    
//La clase phpmailer tiene un pequeño bug y es que cuando envia un mail con
    //attachment la variable ErrorInfo adquiere el valor Data not accepted, dicho 
    //valor no debe confundirnos ya que el mensaje ha sido enviado correctamente
    
if ($mail->ErrorInfo=="SMTP Error: Data not accepted") {
       
$exito=true;
        }
        
    if(!
$exito)
    {
       echo 
"Problemas enviando correo electrónico a ".$valor;
       echo 
"<br>".$mail->ErrorInfo;    
    }
    else
    {
       
//Mostramos un mensaje indicando las direccion de 
       //destino y fichero  adjunto enviado en el mensaje    
       
$mensaje="<p>Has enviado un mensaje a:<br>";
       
$mensaje.=$valor." ";
              
$mensaje.="</p>";
            echo 
$mensaje;


    }
    
// Borro las direcciones de destino establecidas anteriormente
        
$mail->ClearAddresses();
    
    }
    echo 
"<a href='$PHP_SELF'> VOLVER AL FORMULARIO</a>";
   }
   else {
   
?>

   <HTML>
   <BODY>
   <? If ($error) echo "<font color='red'>$error</font>";?>
   <FORM ENCTYPE="multipart/form-data" METHOD="POST" ACTION="<?=$PHP_SELF?>">
                <div align="center">
                    <p style="margin-top: 1px; margin-bottom: 1px">
                    <font color="#FF0000" face="Verdana" size="2"><b>.:Envío de 
                    Información</b></font></p>
                    <table border="0" height="241" bgcolor="#E6E6E6" id="table1" width="381" cellpadding="5">
                        <tr>
                            <td height="22" colspan="2" width="118">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">
                            Empresa</font></b></td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <font size="1" face="Verdana" color="#666666">
                            <input type="text" name="empresa" size="35" style="font-size: 8pt; font-family: Verdana"></font></td>
                        </tr>
                        <tr>
                            <td height="19" colspan="2">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">Envió 
                            Email a</font></b></td>
                            <td height="19" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <font color="#666666">
                            <input type="text" name="email1" size="35" style="font-size: 8pt; font-family: Verdana"></font></td>
                        </tr>
                        <tr>
                            <td height="21" colspan="2">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font face="Verdana" size="1" color="#666666">A la 
                            atención de ...</font></b></td>
                            <td height="21" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <input type="text" name="contacto" size="35" style="font-size: 8pt; font-family: Verdana"></td>
                        </tr>
                        <tr>
                            <td height="142" rowspan="6" width="89">
                            <p style="margin-top: 1px; margin-bottom: 1px">&nbsp;</td>
                            <td height="22" align="center" width="25">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <input type="checkbox" name="info1" value="ON"></td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">&nbsp;Información 
                            Empresa</font></b></td>
                        </tr>
                        <tr>
                            <td height="22" align="center" width="25">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <font face="Verdana" size="1" color="#666666">
                            <input type="checkbox" name="C2" value="ON" style="font-weight: 700"></font></td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">&nbsp;Ultima 
                            Revista</font></b></td>
                        </tr>
                        <tr>
                            <td height="22" align="center" width="25">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <font face="Verdana" size="1" color="#666666">
                            <input type="checkbox" name="C3" value="ON" style="font-weight: 700"></font></td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">&nbsp;Información 
                            Planes de Voz</font></b></td>
                        </tr>
                        <tr>
                            <td height="22" align="center" width="25">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <font face="Verdana" size="1" color="#666666">
                            <input type="checkbox" name="C4" value="ON" style="font-weight: 700"></font></td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">&nbsp;Información 
                            de Blackberry</font></b></td>
                        </tr>
                        <tr>
                            <td height="22" align="center" width="25">
                            <p style="margin-top: 1px; margin-bottom: 1px">
                            <font face="Verdana" size="1" color="#666666">
                            <input type="checkbox" name="C5" value="ON" style="font-weight: 700"></font></td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">&nbsp;Información 
                            de Tarjetas 3G </font></b></td>
                        </tr>
                        <tr>
                            <td height="22" align="center" width="25">
                            <p style="margin-top: 1px; margin-bottom: 1px">&nbsp;</td>
                            <td height="22" width="253">
                            <p style="margin-top: 1px; margin-bottom: 1px"><b>
                            <font size="1" face="Verdana" color="#666666">&nbsp;</font></b></td>
                        </tr>
                    </table>
                </div>
                <p align="center" style="margin-top: 1px; margin-bottom: 1px">
                <input type="submit" value="Enviar" name="enviar">&nbsp;&nbsp;
                <input type="reset" value="Restablecer" name="borrar"></p>
            </form>
   </BODY>
   </HTML>
   <?
   
}
?>
  #4 (permalink)  
Antiguo 08/12/2005, 13:55
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 2 meses
Puntos: 129
Pero estás seguro de que el flujo del código entra al IF():

Código PHP:
    if ($_POST['info1']=="ON")  { 
     
$mail->AddAttachment("documentos/archivo.pdf"); 

Y .. OJO! .. el parámetro que necesita dicho método es un string (ruta de tu archivo) .. así que usalo entre "comillas".

Revisalo .. puedes poner por ejemplo dentro de ese if algo tipo:

die("Pasa al if ..");

Eso dentendrá la ejecución del script en ese punto si es que entra.

Por lo demás y en general . .no sé por qué no usas los arrays superglobales. Eso, si bien ahora no te está dando problemas .. como toques con un servidor con otra configuración (de register_globals) ya no te funcionará el código .. además que estas mezclado uso de acceso a variables externas del script.

Un saludo,
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 02:08.