Foros del Web » Programando para Internet » PHP »

PhpMailer Ayuda, Porfavor!!!

Estas en el tema de PhpMailer Ayuda, Porfavor!!! en el foro de PHP en Foros del Web. Bueno tengo el siguiente codigo php para enviar mail, el problema es que quiero que me llegue a dos correos, al correo que envia el ...
  #1 (permalink)  
Antiguo 10/10/2005, 18:27
 
Fecha de Ingreso: noviembre-2003
Mensajes: 798
Antigüedad: 20 años, 4 meses
Puntos: 8
PhpMailer Ayuda, Porfavor!!!

Bueno tengo el siguiente codigo php para enviar mail, el problema es que quiero que me llegue a dos correos, al correo que envia el mail y a otro correo, el tema es que me lo envia a uno solo y me arroja el siguiente error:

Código:
Has enviado un mensaje a:
[email protected] 
El Mensaje se envió correctamente, estaremos en contácto con Usted, Gracias

Problemas enviando correo electrónico a [email protected]
SMTP Error: The following recipients failed [[email protected]] Volver al Inicio
Código PHP:
if ($enviar) {

    OpenTable2();
    //creamos un array que estará formado por las direcciones de destino
    $direcciones["direccion1"]="[email protected]";
    $direcciones["direccion2"]="[email protected]";      
      //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 = "correo.terra.cl";
      
      //Le indicamos que el servidor smtp requiere autenticación
      $mail->SMTPAuth = false;

      //Le decimos cual es nuestro nombre de usuario y password
      $mail->Username = "[email protected]";
      $mail->Password = "mipassword";
      
      //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 = $nombreper;

      //Asignamos asunto y cuerpo del mensaje
      //El cuerpo del mensaje lo ponemos en formato html, haciendo 
      //que se vea en negrita
      
      $mail->Subject = "From: $email \nReply-To: $adminMail";
    $mensaje = "\n\n$nombreper $apellido($email)";
    $mensaje .= "\n\nTelefono: $telefono";
    $mensaje .= "\n\nTítulo:$titulomsg";
    $mensaje .= "\n\nMensaje:$msg";
    $mensaje = nl2br($mensaje);
      $mail->Body = $mensaje;

      //Definimos AltBody por si el destinatario del correo no admite 
      //email con formato html
      $mail->AltBody =$mensaje;

      //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=120;

      //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." <br/>";

       $mensaje.="El Mensaje se envió correctamente, estaremos en contácto con Usted, Gracias</p>";
         echo $mensaje;


    }
    // Borro las direcciones de destino establecidas anteriormente
        $mail->ClearAddresses();
    
    }
    echo "<a href='$PHP_SELF'> Volver al Inicio</a>";

    CloseTable();
    } 
       else {
 
OpenTable2();

?>
<SCRIPT LANGUAGE="JavaScript">
    <!-- Hide code from non-js browsers
    function validate()
    {
        formObj = document.contact;
        if ((formObj.name.value == "") ||
            (formObj.email.value  == "") ||
            (formObj.subject.value  == "") ||
            (formObj.msg.value  == ""))
        {
            alert("Debe llenar los campos Requeridos");
            return false;
        }
        
        
        /*else {
            alert('<? echo $finishedtext?>');
            return true;
        }*/
    }
    // end hiding -->
</SCRIPT>

<TABLE BORDER=0 cellpadding=5 cellspacing=0>
  <TR>
    <TD>
       <TABLE BORDER=0 cellpadding=2 cellspacing=0>
         <form ENCTYPE="multipart/form-data" action="index.php?modulo=contacto" method="post" name="contact" onSubmit="return validate()">
         <TR>
           <TD>
                <BR>
                <DIV>
                1. Nombre(*)<BR>
                <input type=text size=50 maxlength=50 name=nombreper class='txtfield'><BR>

                2. Apellidos<BR>
                <input type='text' size='50' maxlength='50' name='apellido'><BR>

                3. Direccion de Correo (*)<BR>
                <input type='text' size='50' maxlength='60' name='email'><BR>


                4. Numero Telefono<BR>
                <input type='text' value='(000) 000-0000' size='50' maxlength='32' name='telefono'><BR>


                5. Titulo (*)<BR>
                <input type='text' value='' size='50' maxlength='60' name='titulomsg'><BR>


                6. Mensaje (*)<BR>
                <textarea name='msg' rows='7' cols='50'></textarea><BR>

                </DIV>

                <input type='submit' name='enviar' value='Enviar'><BR><BR>(*) Campos Requeridos

          </TD>
        </tR>
        </FORM>
      </tABLE>
    </TD>
  </TR>
</tABLE>
<?php
CloseTable
();
}
?>
cualquier ayuda muchisimas gracias, ya que es urgente.

salu2
  #2 (permalink)  
Antiguo 10/10/2005, 19:57
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 3 meses
Puntos: 129
Bueno, tu código funciona perfectamente .. lo que no funciona bien es esa cuenta que pretendes enviar el 2° mail .. De hecho se te está devolviendo código de error que obtienes. Revisa esa cuenta.

Un saludo,
  #3 (permalink)  
Antiguo 10/10/2005, 20:32
 
Fecha de Ingreso: noviembre-2003
Mensajes: 798
Antigüedad: 20 años, 4 meses
Puntos: 8
Cita:
Iniciado por Cluster
Bueno, tu código funciona perfectamente .. lo que no funciona bien es esa cuenta que pretendes enviar el 2° mail .. De hecho se te está devolviendo código de error que obtienes. Revisa esa cuenta.

Un saludo,
Que tengo que configurar para que se envie a ambas cuentas?, y que pasa si tuviera que enviar a varios mails, porque probé con distintos mails y con todos me lanza el error en el 2º mail.


saludos y muchas gracias.
  #4 (permalink)  
Antiguo 10/10/2005, 21:01
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 3 meses
Puntos: 129
Pues no tienes que configurar nada. .. Tenías que haber dicho -antes- que te sucede siempre que envias el 2° mail.

Pero .. lo dicho .. en principio ese error lo dá la conexión SMTP.

Lo que no me parece correcto es:
$mail->Subject = "From: $email \nReply-To: $adminMail";

Bueno .. como "Asunto" de un e-mail .. podría pasar .. pero un \n (salto de línea) no corresponde.

Sobre esos comentarios de "bug" de PHP Mailer . .revisa que versión estás usando .. e intenta usar la última que está disponible (http://phpmailer.sourceforge.net) creo que eso que mencionas ahí ya está solucionado.

Tal vez por ahí venga también tu problema .. consulta en los foros de esa classe.

Un saludo,
  #5 (permalink)  
Antiguo 11/10/2005, 09:57
 
Fecha de Ingreso: noviembre-2003
Mensajes: 798
Antigüedad: 20 años, 4 meses
Puntos: 8
ahora me cambié a la ultima version 1.73 y me aparece otro mensaje de error:
Código PHP:
Problemas enviando correo electr&#243;nico a [email protected]
Language string failed to loadrecipients_failedesteban.bayor@lumni.cl Volver al Inicio 
se me olvidó mencionar lo siguiente del archivo class.phpmailer.php:

Código PHP:
class PHPMailer
{
    
/////////////////////////////////////////////////
    // PUBLIC VARIABLES
    /////////////////////////////////////////////////

    /**
     * Email priority (1 = High, 3 = Normal, 5 = low).
     * @var int
     */
    
var $Priority          3;

    
/**
     * Sets the CharSet of the message.
     * @var string
     */
    
var $CharSet           "iso-8859-1";

    
/**
     * Sets the Content-type of the message.
     * @var string
     */
    
var $ContentType        "text/plain";

    
/**
     * Sets the Encoding of the message. Options for this are "8bit",
     * "7bit", "binary", "base64", and "quoted-printable".
     * @var string
     */
    
var $Encoding          "8bit";

    
/**
     * Holds the most recent mailer error message.
     * @var string
     */
    
var $ErrorInfo         "";

    
/**
     * Sets the From email address for the message.
     * @var string
     */
    
var $From               "root@localhost";

    
/**
     * Sets the From name of the message.
     * @var string
     */
    
var $FromName           "Root User";

    
/**
     * Sets the Sender email (Return-Path) of the message.  If not empty,
     * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
     * @var string
     */
    
var $Sender            "";

    
/**
     * Sets the Subject of the message.
     * @var string
     */
    
var $Subject           "";

    
/**
     * Sets the Body of the message.  This can be either an HTML or text body.
     * If HTML then run IsHTML(true).
     * @var string
     */
    
var $Body               "";

    
/**
     * Sets the text-only body of the message.  This automatically sets the
     * email to multipart/alternative.  This body can be read by mail
     * clients that do not have HTML email capability such as mutt. Clients
     * that can read HTML will view the normal Body.
     * @var string
     */
    
var $AltBody           "";

    
/**
     * Sets word wrapping on the body of the message to a given number of 
     * characters.
     * @var int
     */
    
var $WordWrap          0;

    
/**
     * Method to send mail: ("mail", "sendmail", or "smtp").
     * @var string
     */
    
var $Mailer            "mail";

    
/**
     * Sets the path of the sendmail program.
     * @var string
     */
    
var $Sendmail          "/usr/sbin/sendmail";
    
    
/**
     * Path to PHPMailer plugins.  This is now only useful if the SMTP class 
     * is in a different directory than the PHP include path.  
     * @var string
     */
    
var $PluginDir         "";

    
/**
     *  Holds PHPMailer version.
     *  @var string
     */
    
var $Version           "1.73";

    
/**
     * Sets the email address that a reading confirmation will be sent.
     * @var string
     */
    
var $ConfirmReadingTo  "";

    
/**
     *  Sets the hostname to use in Message-Id and Received headers
     *  and as default HELO string. If empty, the value returned
     *  by SERVER_NAME is used or 'localhost.localdomain'.
     *  @var string
     */
    
var $Hostname          "";

    
/////////////////////////////////////////////////
    // SMTP VARIABLES
    /////////////////////////////////////////////////

    /**
     *  Sets the SMTP hosts.  All hosts must be separated by a
     *  semicolon.  You can also specify a different port
     *  for each host by using this format: [hostname:port]
     *  (e.g. "smtp1.example.com:25;smtp2.example.com").
     *  Hosts will be tried in order.
     *  @var string
     */
    
var $Host        "localhost";

    
/**
     *  Sets the default SMTP server port.
     *  @var int
     */
    
var $Port        25;

    
/**
     *  Sets the SMTP HELO of the message (Default is $Hostname).
     *  @var string
     */
    
var $Helo        "";

    
/**
     *  Sets SMTP authentication. Utilizes the Username and Password variables.
     *  @var bool
     */
    
var $SMTPAuth     false;

    
/**
     *  Sets SMTP username.
     *  @var string
     */
    
var $Username     "";

    
/**
     *  Sets SMTP password.
     *  @var string
     */
    
var $Password     "";

    
/**
     *  Sets the SMTP server timeout in seconds. This function will not 
     *  work with the win32 version.
     *  @var int
     */
    
var $Timeout      10;

    
/**
     *  Sets SMTP class debugging on or off.
     *  @var bool
     */
    
var $SMTPDebug    false;

    
/**
     * Prevents the SMTP connection from being closed after each mail 
     * sending.  If this is set to true then to close the connection 
     * requires an explicit call to SmtpClose(). 
     * @var bool
     */
    
var $SMTPKeepAlive false
estas variables y en especial
Código PHP:
var $From               "root@localhost";
var 
$Host        "localhost";
    var 
$SMTPAuth     false;

    
/**
     *  Sets SMTP username.
     *  @var string
     */
    
var $Username     "";

    
/**
     *  Sets SMTP password.
     *  @var string
     */
    
var $Password     ""
se tienen que configurar tambien? o es suficiente con la configuracion del script anterior?

PD:El script esta en un hosting de pago, no en local.

Última edición por zsamer; 11/10/2005 a las 10:36
  #6 (permalink)  
Antiguo 11/10/2005, 10:35
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 3 meses
Puntos: 129
Esas variables de PHP Mailer "$From y $FromName" ya le das valor en tu script. Esos valores son "por defecto" por si no definieses tu expresamente esos valores ("DE e-mail" y "De nombre").

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 12:36.