Foros del Web » Programación para mayores de 30 ;) » Java »

Problemas con JavaMail (auntetificacion)

Estas en el tema de Problemas con JavaMail (auntetificacion) en el foro de Java en Foros del Web. que tal, pues ahora lo que intento es poder mandar un mail, ya lei la documentacion de javamail, y busque un ejemplito (sin autentificacion) para ...
  #1 (permalink)  
Antiguo 24/01/2006, 13:45
 
Fecha de Ingreso: noviembre-2003
Ubicación: Mexico
Mensajes: 1.081
Antigüedad: 20 años, 5 meses
Puntos: 7
Problemas con JavaMail (auntetificacion)

que tal, pues ahora lo que intento es poder mandar un mail, ya lei la documentacion de javamail, y busque un ejemplito (sin autentificacion) para mandar un mail.
Y yo lo modifique para que se auntenticar de un correo de Yahoo a otro de Yahoo, pero me manda este error:
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
at javax.mail.Service.connect(Service.java:156)
at TestEmail.main(TestEmail.java:51)
Press any key to continue...

este es el codigo:
Código PHP:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

// Send a simple, single part, text/plain e-mail
public class TestEmail {

    public static 
void main(String[] args) {

        
// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
        
String to "[email protected]";
        
String from "[email protected]";
        
String pass "mipass";
        
// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
        
String host "smtp.mail.yahoo.com";

        
// Create properties, get Session
        
Properties props = new Properties();

        
// If using static Transport.send(),
        // need to specify which host to send it to
        
props.put("mail.smtp.host"host);
        
// To see what is going on behind the scene
        //props.put("mail.debug", "true");
        
props.put("mail.smtp.auth","true");
        
Session session Session.getInstance(props);

        
        try {
            
// Instantiatee a message
            
Message msg = new MimeMessage(session);
            
            
            
            
            
//Set message attributes
            
msg.setFrom(new InternetAddress(from));
            
InternetAddress[] address = {new InternetAddress(to)};
            
msg.setRecipients(Message.RecipientType.TOaddress);
            
msg.setSubject("Test E-Mail through Java");
            
msg.setSentDate(new Date());

            
// Set message content
            
msg.setText("This is a test of sending a " +
                        
"plain text e-mail through Java.\n" +
                        
"Here is line 2.");
                        
            
Transport trans session.getTransport(address[0]);
            
            
trans.connect(host,from,pass);
            
//trans.send(msg);
            
trans.sendMessage(msg,address);
            
            
//Send the message
            //Transport.send(msg);
        
}
        catch (
MessagingException mex) {
            
// Prints all nested (chained) exceptions as well
            
mex.printStackTrace();
        }
    }
}
//End of class 
No se que estoy haciendo mal, o si alguien me puede decir como.....
p.d: obviamente en el programa original pongo bien mi username y password jeje..

saludos,
  #2 (permalink)  
Antiguo 24/01/2006, 14:09
Avatar de NanoWare  
Fecha de Ingreso: octubre-2005
Mensajes: 19
Antigüedad: 18 años, 6 meses
Puntos: 0
Sonrisa autenticacion con Javamail

BlackWind...

prueba esta instruccion, ami me funciona perfectamente:

props.put("mail.smtp.auth","true");
//estas son las lineas agregadas
sistemas auth = new sistemas();
Session session = Session.getInstance(props , auth);

al final agregas esta clase

class sistemas extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
String username = "[email protected]";
String password = "password";

return new PasswordAuthentication(username, password);
}
}


como ves se instancia una llamada la clase sistemas que extiende la clase de autenticacion, con la cual se obtienen los datos de usuario y password, los cuales se instancian finalmente en la construccion del mensaje para su envio por medio del objeto session
  #3 (permalink)  
Antiguo 24/01/2006, 14:41
 
Fecha de Ingreso: noviembre-2003
Ubicación: Mexico
Mensajes: 1.081
Antigüedad: 20 años, 5 meses
Puntos: 7
ya probe, pero me sigue mandando el mismo error :S
alguna otra solucion?
  #4 (permalink)  
Antiguo 25/01/2006, 09:07
 
Fecha de Ingreso: octubre-2005
Mensajes: 188
Antigüedad: 18 años, 6 meses
Puntos: 0
Mira este codigo a ver
Código PHP:
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class 
MailExample1 {
public static 
void main (String args[]) throws Exception {
String host args[0];
String from args[1];
String to args[2];

// Get system properties
Properties props System.getProperties();

// Setup mail server
props.put("mail.smtp.host"host);
Authenticator auth = new MyAuthenticator();

// Get session 
Session session Session.getDefaultInstance(propsauth);

// Define message
MimeMessage message = new MimeMessage(session);

// Set the from address
message.setFrom(new InternetAddress(from));

// Set the to address
message.addRecipient(Message.RecipientType.TO
new 
InternetAddress(to));

// Set the subject
message.setSubject("Hello");

// Set the content
message.setText("Welcome");

// Send message
Transport.send(message);
}


static class 
MyAuthenticator extends Authenticator {
PasswordAuthentication l = new PasswordAuthentication("username""password"); 
protected 
PasswordAuthentication getPasswordAuthentication() {
return 
l;
}
}

Basicamente es el mismo ke puso NanoWare salvo por una linea en la ultima clase, a mi me funciona.
  #5 (permalink)  
Antiguo 25/01/2006, 10:56
 
Fecha de Ingreso: noviembre-2003
Ubicación: Mexico
Mensajes: 1.081
Antigüedad: 20 años, 5 meses
Puntos: 7
Sigue sin funcionarme.
Lei que com yahoo y hotmail no se, y con gmail si, asi que cambie.
Pero aun asi no funciona,
agregue estas lineas de codigo:

props.put("mail.smtp.debug", "true");
props.put("mail.smtp.port","465");
props.put("mail.smtps.auth","true");

session.setDebug(true);

y no funciona. Se queda tratando de establecer la conexion.

Lo extranio es que baje otra libreria llamada
Secure iNet Factory y con esa funciona a la perfeccion, el problema es que es de paga y vale 1000 dollares.

Me pueden decir con que servidor probaron que si les funcione su codigo??
es decir, su codigo tal cual (a excepcion de su password y username)

saludos,
  #6 (permalink)  
Antiguo 25/01/2006, 14:35
 
Fecha de Ingreso: enero-2006
Mensajes: 2
Antigüedad: 18 años, 3 meses
Puntos: 0
Hola a todos:

Ojo, Si tu correo realmente es de yahoo ni lo sigas intentando, yahoo no permite la autenticacion al igual que gmail, debes buscar un servidor de correo que si lo permita

Me cuentan
  #7 (permalink)  
Antiguo 26/01/2006, 13:47
 
Fecha de Ingreso: noviembre-2003
Ubicación: Mexico
Mensajes: 1.081
Antigüedad: 20 años, 5 meses
Puntos: 7
aun cuando necesiten autntificacion se puede.
Si se puede configurr el outlook para recibir, entonces se puede crear un programa que lo haga.
Y como decia, con la libreria esa que baje, con google me funciona a la perfeccion. Pero ya haciendolo con javamail no sale...........

alguien tiene un codigo para un servidor especifico que si funcione?
  #8 (permalink)  
Antiguo 26/01/2006, 17:57
 
Fecha de Ingreso: junio-2005
Mensajes: 286
Antigüedad: 18 años, 10 meses
Puntos: 2
Puede ser que el servidor (SMTP) requiera autentificacion por medio de SSL/TLS. Quizas esa libreria privada implementa esta autentificacion segura ("Secure") por medio de SSL/TLS.

No se si hay implementacion SSL en Java, seguro que si la hay. Haz un Google.
  #9 (permalink)  
Antiguo 26/01/2006, 21:24
 
Fecha de Ingreso: noviembre-2003
Ubicación: Mexico
Mensajes: 1.081
Antigüedad: 20 años, 5 meses
Puntos: 7
excelente willie, muchas gracias.
Eso era lo que necesitaba y ya me quedo.

Por si a alguien le interesa, aqui les dejo el codigo
package com.radicalsoftware.rademailhosting;

Código PHP:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/***********************************************
/* JavaMail SSL + Authentication - Example Code
/************************************************/
public class Mailer
{

    public static 
void main(String[] args)
    {
        
Mailer obj = new Mailer();
        
String server "smtp.gmail.com";
        
String userName "[email protected]";
        
String password "password";
        
String fromAddres "perenganito";
        
String toAddres "[email protected]";
        
String cc "";
        
String bcc "";
        
boolean htmlFormat false;
        
String subject "tema";
        
String body "prueba";
        
        
obj.sendMail(serveruserNamepasswordfromAddrestoAddresccbcc,
                     
htmlFormatsubjectbody);
        
    }

    public 
void sendMail(String serverString userNameString passwordString fromAddressString toAddressString ccString bccboolean htmlFormatString subjectString body)
    {
    
        
Properties properties System.getProperties();
        
properties.put("mail.smtps.host"server);
        
properties.put("mail.smtps.auth""true");
        
Session ses  Session.getInstance(properties);

        
ses.setDebug(true);

        try{
        
            
MimeMessage msg = new MimeMessage(ses);
    
            
msg.setFrom(new InternetAddress(fromAddress));
    
            if (
toAddress != null)
            {
               
msg.addRecipients(Message.RecipientType.TOtoAddress);
            }
    
            if (
cc != null)
            {
                
msg.setRecipients(Message.RecipientType.CC
                        
,InternetAddress.parse(ccfalse));
            }
    
            if (
bcc != null)
            {
                
msg.setRecipients(Message.RecipientType.BCC
                        
,InternetAddress.parse(bccfalse));
            }
    
            if (
htmlFormat)
            {
                
msg.setContent(body"text/html");
            }
            else
            {
                
msg.setContent(body"text/plain");
            }
    
            
msg.setSubject(subject);
            
msg.saveChanges();
    
            
Transport tr ses.getTransport("smtps");
            
tr.connect(server,userNamepassword);
            
tr.sendMessage(msgmsg.getAllRecipients());
            
tr.close();
        }
        
        catch(
MessagingException e)
        {
            
e.printStackTrace();
        }
        
        

    }
}

class 
MyPasswordAuthenticator extends Authenticator
{
   
String user;
   
String pw;

   public 
MyPasswordAuthenticator (String usernameString password)
   {
      
super();
      
this.user username;
      
this.pw password;
   }
   public 
PasswordAuthentication getPasswordAuthentication()
   {
      return new 
PasswordAuthentication(userpw);
   }

saludos,
  #10 (permalink)  
Antiguo 28/01/2006, 11:40
 
Fecha de Ingreso: octubre-2005
Mensajes: 188
Antigüedad: 18 años, 6 meses
Puntos: 0
Una pregunta blackwind ese pakete ke mencionas, es para empaketar la aplicacion, no veo ke lo importes. Segundo en donde se hace el llamado al puerto 465 de gmail, o es ke automaticamente busca ese puerto (me imagino ke sera el ke usa gmail), xq estoy tratando de usar tu codigo con mi servidor de correos y no me funciona me dice connection refused xq el intenta abrir es el puerto 465 de mi servidor y ese no es el ke el usa sino el 25. Agradezco me puedas aclarar estas dudas.
PD: enviando correo desde este codigo hacia el servidor de mi universidad si funciona.
  #11 (permalink)  
Antiguo 28/01/2006, 12:29
 
Fecha de Ingreso: octubre-2003
Mensajes: 3.578
Antigüedad: 20 años, 6 meses
Puntos: 51
SMTP -> Puerto 25
SMTPS -> Puerto 465

Si el puerto 465 no responde seguramente es por que tu universidad el servidor no tenga habilitado el protocolo SMTPS
  #12 (permalink)  
Antiguo 28/01/2006, 22:20
 
Fecha de Ingreso: noviembre-2003
Ubicación: Mexico
Mensajes: 1.081
Antigüedad: 20 años, 5 meses
Puntos: 7
ademas de lo que dijo willie, ya estuve checando algunas pruebas, y la parte clave del codigo es esta:


Transport trans = session.getTransport("smtps");

si haces eso, automaticamente buscara el puerto 465 con SSL true (que es lo que gmail necesita), si no haces eso, aun cuando especifiques el puerto 465, el SSL sera "false", y no podras establecer la conexion.

De hecho, en el primer codigo que puse, si cambias esta linea:
Transport trans = session.getTransport(address[0]);
por la que puse arriba, y esta:
props.put("mail.smtp.host", host);
por:
props.put("mail.smtps.host", host);

(con la "s")
tambien funcionara.

Espero que te sirva
saludos,
  #13 (permalink)  
Antiguo 30/01/2006, 09:21
 
Fecha de Ingreso: octubre-2005
Mensajes: 188
Antigüedad: 18 años, 6 meses
Puntos: 0
Ke mas a todos, blackwind probe tu codigo (el primero ke pusiste) con los cambios ke mencionaste y no me funciona, greeneyed debe tener razon de pronto el servidor de mi universidad no tiene habilitado dicho protocolo; sin cambiar las lineas ke mencionas si me funciona pero solo hacia mi servidor si intento enviar correo hacia otro no me funciona sigue con el relay denied. Por ahi lei algo ke para ke le permita enviar correo hay ke autentificarse primero por medio de pop3, es decir ingresar y bajar el correo, algo llamado pop3 before smtp, pero nada lo hice asi y sigue sin dejarme enviar correo hacia otros servidores, con el error ke ya mencione antes.
  #14 (permalink)  
Antiguo 30/01/2006, 15:28
 
Fecha de Ingreso: noviembre-2003
Ubicación: Mexico
Mensajes: 1.081
Antigüedad: 20 años, 5 meses
Puntos: 7
no se, ni idea de que pueda estar pasando.....
  #15 (permalink)  
Antiguo 30/01/2006, 16:18
 
Fecha de Ingreso: octubre-2003
Mensajes: 3.578
Antigüedad: 20 años, 6 meses
Puntos: 51
Es probablemente una cuestion de configuracion del servidor de correo. En mi universidad el servidor de correo solo te permite enviar mensajes de correo a direcciones fuera de la universidad si estas DENTRO de la red de la universidad. Y de ninguna de las maneras te deja enviar un mensaje si en el from no pone una direccion de la universidad.

Todo eso lo hacen para prevenir que los spammers usen los servidores de correo de la universidad para enviar sus mensajes masivos, y el mensaje de error que devuelve es... adivina ;)
  #16 (permalink)  
Antiguo 27/02/2007, 23:54
 
Fecha de Ingreso: febrero-2007
Mensajes: 1
Antigüedad: 17 años, 2 meses
Puntos: 0
Re: Problemas con JavaMail (auntetificacion)

Encontré la solución, para correos que usan stmps(seguro) y smtp normal, el smtps de google ocupa el puerto 465 que se ha mencionado anteriormente en este foro, les dejo el codigo para funcionar con google, si desean cambiar a otro servidor de correo con smtp normarl que usa el puerto 25 solo deben modificar la linea :
boolean ssl = true;
y ponerla como
boolean ssl = false;
y obviamente el nombre de usuario y contraseña
si tienen bien instaladas las librerias javamail y una salida a internet sin los puertos 25 y 465 bloquedos, seguro que funciona

Código PHP:

String to 
mail;     // to address 
        
String from "[email protected]"// fromaddress 
        
String subject "Titulo del correo";  
        
String message "<b>Mensaje de prueba</b><br><h1>Hola></h1>";
        
String mailhost "smtp.gmail.com"// servidor smtp de gmail(smtps), pero en esta linea no lleva la "s" de "smtps"
        
String user "[email protected]"// Aqui va tu nombre de usuario, observa que va tambien "@gmail.com" no solamente el nombre de usuario
        
String password "xxxx";              // Aqui va tu password

        // in the case of an exception, print a message to the output log 
        
boolean auth true;
        
boolean ssl true;
        
Properties props System.getProperties();
        
        if (
mailhost != null){
            
props.put("mail.smtp.host"mailhost);
            
props.put("mail.smtps.host"mailhost);
        }
        if (
auth){
            
props.put("mail.smtp.auth""true");
            
props.put("mail.smtps.auth""true");
        }
        
        
props.put("mail.smtp.port""25");
        
props.put("mail.smtps.port""465");
        
        
// Get a Session object
        
javax.mail.Session session javax.mail.Session.getInstance(props);
        
session.setDebug(true); 
   
        
// construct the message
        
javax.mail.Message msg = new MimeMessage(session);
        
        try {
            
//  Set message details
            
msg.setFrom(new InternetAddress(from));
            
msg.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
            
msg.setSubject(subject);
            
msg.setSentDate(new Date());
            
msg.setContent(message"text/html");
            
//msg.setText(message);
                    
            // send the thing off
            
SMTPTransport t =
                    (
SMTPTransport)session.getTransport(ssl "smtps" "smtp"); //si ssl=true, smtps si no smtp
            
try {
                if (
auth)
                    
t.connect(mailhostuserpassword);
                else
                    
t.connect();
                
t.sendMessage(msgmsg.getAllRecipients());
            } 
finally {
                
t.close();
            }
            
log("Mail was sent successfully.");
            
        } catch (
Exception e) {
            if (
instanceof SendFailedException) {
                
MessagingException sfe = (MessagingException)e;
                if (
sfe instanceof SMTPSendFailedException) {
                    
SMTPSendFailedException ssfe =
                            (
SMTPSendFailedException)sfe;
                    
log("SMTP SEND FAILED:");
                }
                
Exception ne;
                while ((
ne sfe.getNextException()) != null &&
                    
ne instanceof MessagingException)     {
            
sfe = (MessagingException)ne;
            if (
sfe instanceof SMTPAddressFailedException) {
            
SMTPAddressFailedException ssfe =
                    (
SMTPAddressFailedException)sfe;
            
log("ADDRESS FAILED:");
            
log(ssfe.toString());
            
log("  Address: " ssfe.getAddress());
            
log("  Command: " ssfe.getCommand());
            
log("  RetCode: " ssfe.getReturnCode());
            
log("  Response: " ssfe.getMessage());
            } else if (
sfe instanceof SMTPAddressSucceededException) {
            
log("ADDRESS SUCCEEDED:");
            
SMTPAddressSucceededException ssfe =
                    (
SMTPAddressSucceededException)sfe;
            }
                }
        } else {
            
log("Got Exception : " e);       
          }
        } 
Ami me funcionó a la perfección, espero que les funcione.
  #17 (permalink)  
Antiguo 05/03/2007, 10:15
 
Fecha de Ingreso: julio-2006
Ubicación: Argentina
Mensajes: 35
Antigüedad: 17 años, 9 meses
Puntos: 0
Re: Problemas con JavaMail (auntetificacion)

Holas amigos espectacular la solucion!!
Ya creia que no se podia mandar mensajes a gmail, ahora creia que hiba a andar todo bien despues de probar tantas veces, pero me sigue tirando siempre el mismo error, aun asi probando el codigo que ustedes facilitaron, creo que debe ser otra cosa pero no se que es.

EL error es el siguiente:

13:14:15,593 INFO [STDOUT] javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first g5sm9232994wra
13:14:15,609 INFO [STDOUT] at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPT ransport.java:879)
13:14:15,609 INFO [STDOUT] at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTrans port.java:599)
13:14:15,609 INFO [STDOUT] at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTr ansport.java:319)
13:14:15,609 INFO [STDOUT] at com.ombuSCR.mail.IMPLEMENTATION.MailImplementation .sendMail(MailImplementation.java:283)
13:14:15,609 INFO [STDOUT] at com.ombuSCR.mail.ACTION.MailAction.linkEnviarMail( MailAction.java:68)
13:14:15,609 INFO [STDOUT] at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
13:14:15,609 INFO [STDOUT] at sun.reflect.NativeMethodAccessorImpl.invoke(Native MethodAccessorImpl.java:39)
13:14:15,609 INFO [STDOUT] at sun.reflect.DelegatingMethodAccessorImpl.invoke(De legatingMethodAccessorImpl.java:25)
13:14:15,609 INFO [STDOUT] at java.lang.reflect.Method.invoke(Method.java:585)
13:14:15,609 INFO [STDOUT] at org.apache.struts.actions.DispatchAction.dispatchM ethod(DispatchAction.java:274)
13:14:15,609 INFO [STDOUT] at org.apache.struts.actions.DispatchAction.execute(D ispatchAction.java:194)
13:14:15,609 INFO [STDOUT] at org.apache.struts.action.RequestProcessor.processA ctionPerform(RequestProcessor.java:419)
13:14:15,625 INFO [STDOUT] at org.apache.struts.action.RequestProcessor.process( RequestProcessor.java:224)
13:14:15,625 INFO [STDOUT] at org.apache.struts.action.ActionServlet.process(Act ionServlet.java:1194)
13:14:15,625 INFO [STDOUT] at org.apache.struts.action.ActionServlet.doPost(Acti onServlet.java:432)
13:14:15,625 INFO [STDOUT] at javax.servlet.http.HttpServlet.service(HttpServlet .java:717)
13:14:15,625 INFO [STDOUT] at javax.servlet.http.HttpServlet.service(HttpServlet .java:810)
13:14:15,625 INFO [STDOUT] at org.apache.catalina.core.ApplicationFilterChain.in ternalDoFilter(ApplicationFilterChain.java:252)
13:14:15,625 INFO [STDOUT] at org.apache.catalina.core.ApplicationFilterChain.do Filter(ApplicationFilterChain.java:173)
13:14:15,625 INFO [STDOUT] at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doF ilter(ReplyHeaderFilter.java:81)
13:14:15,625 INFO [STDOUT] at org.apache.catalina.core.ApplicationFilterChain.in ternalDoFilter(ApplicationFilterChain.java:202)
13:14:15,625 INFO [STDOUT] at org.apache.catalina.core.ApplicationFilterChain.do Filter(ApplicationFilterChain.java:173)
13:14:15,625 INFO [STDOUT] at org.apache.catalina.core.StandardWrapperValve.invo ke(StandardWrapperValve.java:213)
13:14:15,625 INFO [STDOUT] at org.apache.catalina.core.StandardContextValve.invo ke(StandardContextValve.java:178)
13:14:15,640 INFO [STDOUT] at org.jboss.web.tomcat.security.CustomPrincipalValve .invoke(CustomPrincipalValve.java:39)
13:14:15,640 INFO [STDOUT] at org.jboss.web.tomcat.security.SecurityAssociationV alve.invoke(SecurityAssociationValve.java:153)
13:14:15,640 INFO [STDOUT] at org.jboss.web.tomcat.security.JaccContextValve.inv oke(JaccContextValve.java:59)
13:14:15,640 INFO [STDOUT] at org.apache.catalina.core.StandardHostValve.invoke( StandardHostValve.java:126)
13:14:15,671 INFO [STDOUT] at org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:105)
13:14:15,671 INFO [STDOUT] at org.apache.catalina.core.StandardEngineValve.invok e(StandardEngineValve.java:107)
13:14:15,671 INFO [STDOUT] at org.apache.catalina.connector.CoyoteAdapter.servic e(CoyoteAdapter.java:148)
13:14:15,671 INFO [STDOUT] at org.apache.coyote.http11.Http11Processor.process(H ttp11Processor.java:856)
13:14:15,671 INFO [STDOUT] at org.apache.coyote.http11.Http11Protocol$Http11Conn ectionHandler.processConnection(Http11Protocol.jav a:744)
13:14:15,671 INFO [STDOUT] at org.apache.tomcat.util.net.PoolTcpEndpoint.process Socket(PoolTcpEndpoint.java:527)
13:14:15,671 INFO [STDOUT] at org.apache.tomcat.util.net.MasterSlaveWorkerThread .run(MasterSlaveWorkerThread.java:112)
13:14:15,671 INFO [STDOUT] at java.lang.Thread.run(Thread.java:595)

POr favor ayudenmen, me esta volviendo loco estoo!
  #18 (permalink)  
Antiguo 21/03/2007, 12:03
 
Fecha de Ingreso: julio-2006
Ubicación: Argentina
Mensajes: 35
Antigüedad: 17 años, 9 meses
Puntos: 0
Re: Problemas con JavaMail (auntetificacion)

Ahora si tengo problemas de autentificacion, maldicion!!! haaaaaaaaaaaaaaa, tengo MyEclipse + JavaMail 1.4, y me tira este error:

14:51:39,406 INFO [STDOUT] com.sun.mail.smtp.SMTPSendFailedException: 530 5.5.1 Authentication Required 24sm3535897wrl

El codigo del programa es este:

Código PHP:
public void sendMail(String tothrows MessagingException{    
        
        
String from "[email protected]"
        
String subject "Titulo del correo";   
        
String message "<b>Mensaje de prueba</b><br><h1>Hola></h1>"
       
String mailhost "smtp.gmail.com"
       
String user "[email protected]";         
                
String password "pass";              
    
         
        
boolean auth true
        
boolean ssl true
        
boolean STARTTLS true;
        
      
        
        
Properties props System.getProperties(); 
         
        if (
mailhost != null){ 
            
props.put("mail.smtp.host"mailhost); 
            
props.put("mail.smtps.host"mailhost); 
        } 
        if (
auth){ 
            
props.put("mail.smtp.auth"auth);  
            
props.put("mail.smtps.auth"auth); 
        } 
     
        
props.put("mail.smtp.port""25"); 
        
props.put("mail.smtps.port""465");
        
props.put("mail.smtps.STARTTLS.enable"STARTTLS);
        
         
        
// Get a Session object 
        
        
javax.mail.Session session javax.mail.Session.getInstance(props); 
        
session.setDebug(true);  
    
        
// construct the message 
        
javax.mail.Message msg = new MimeMessage(session); 
         
        try { 
            
//  Set message details 
            
msg.setFrom(new InternetAddress(from)); 
            
msg.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); 
            
msg.setSubject(subject); 
            
msg.setSentDate(new Date()); 
            
msg.setContent(message"text/html"); 
            
//msg.setText(message); 
            
msg.saveChanges();
                     
            
// send the thing off 
            //SMTPTransport t = (SMTPTransport)session.getTransport("smtps"); 
          

            
            
SMTPTransport t = (SMTPTransport)session.getTransport(ssl "smtps" "smtp"); //si ssl=true, smtps si no smtp         
            
            
try { 
                if (
auth){ 
                    
t.connect(mailhostuserpassword);
                }else{ 
                    
t.connect();
                }
                
t.sendMessage(msgmsg.getAllRecipients()); 
            } 
finally 
                
t.close(); 
            } 
           
             
        } catch (
Exception e) { 
            if (
instanceof SendFailedException) { 
                
MessagingException sfe = (MessagingException)e
                
Exception ne
                while ((
ne sfe.getNextException()) != null && 
                    
ne instanceof MessagingException){ 
                        
sfe = (MessagingException)ne
                         } 
             } 
            
e.printStackTrace();
        }  
          
    
    } 
Por favor ayudenmen!!
  #19 (permalink)  
Antiguo 19/03/2008, 14:33
Avatar de genco  
Fecha de Ingreso: febrero-2008
Mensajes: 9
Antigüedad: 16 años, 3 meses
Puntos: 0
Re: Problemas con JavaMail (auntetificacion)

blackwind n que parte de tu codigo llamas a MyPasswordAuthenticator? estas seguro que es el codigo que te funciona?

Cita:
Iniciado por blackwind Ver Mensaje
excelente willie, muchas gracias.
Eso era lo que necesitaba y ya me quedo.

Por si a alguien le interesa, aqui les dejo el codigo
package com.radicalsoftware.rademailhosting;

Código PHP:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/***********************************************
/* JavaMail SSL + Authentication - Example Code
/************************************************/
public class Mailer
{

    public static 
void main(String[] args)
    {
        
Mailer obj = new Mailer();
        
String server "smtp.gmail.com";
        
String userName "[email protected]";
        
String password "password";
        
String fromAddres "perenganito";
        
String toAddres "[email protected]";
        
String cc "";
        
String bcc "";
        
boolean htmlFormat false;
        
String subject "tema";
        
String body "prueba";
        
        
obj.sendMail(serveruserNamepasswordfromAddrestoAddresccbcc,
                     
htmlFormatsubjectbody);
        
    }

    public 
void sendMail(String serverString userNameString passwordString fromAddressString toAddressString ccString bccboolean htmlFormatString subjectString body)
    {
    
        
Properties properties System.getProperties();
        
properties.put("mail.smtps.host"server);
        
properties.put("mail.smtps.auth""true");
        
Session ses  Session.getInstance(properties);

        
ses.setDebug(true);

        try{
        
            
MimeMessage msg = new MimeMessage(ses);
    
            
msg.setFrom(new InternetAddress(fromAddress));
    
            if (
toAddress != null)
            {
               
msg.addRecipients(Message.RecipientType.TOtoAddress);
            }
    
            if (
cc != null)
            {
                
msg.setRecipients(Message.RecipientType.CC
                        
,InternetAddress.parse(ccfalse));
            }
    
            if (
bcc != null)
            {
                
msg.setRecipients(Message.RecipientType.BCC
                        
,InternetAddress.parse(bccfalse));
            }
    
            if (
htmlFormat)
            {
                
msg.setContent(body"text/html");
            }
            else
            {
                
msg.setContent(body"text/plain");
            }
    
            
msg.setSubject(subject);
            
msg.saveChanges();
    
            
Transport tr ses.getTransport("smtps");
            
tr.connect(server,userNamepassword);
            
tr.sendMessage(msgmsg.getAllRecipients());
            
tr.close();
        }
        
        catch(
MessagingException e)
        {
            
e.printStackTrace();
        }
        
        

    }
}

class 
MyPasswordAuthenticator extends Authenticator
{
   
String user;
   
String pw;

   public 
MyPasswordAuthenticator (String usernameString password)
   {
      
super();
      
this.user username;
      
this.pw password;
   }
   public 
PasswordAuthentication getPasswordAuthentication()
   {
      return new 
PasswordAuthentication(userpw);
   }

saludos,
  #20 (permalink)  
Antiguo 19/03/2008, 14:42
 
Fecha de Ingreso: octubre-2003
Mensajes: 3.578
Antigüedad: 20 años, 6 meses
Puntos: 51
Re: Problemas con JavaMail (auntetificacion)

En dos días hará un año del ultimo mensaje en este hilo, mas de dos desde el ultimo mensade de BlackWind . Sólo espero que si se quedó a ver si le respondían, alguien le trajera comida, .
__________________
Para obtener respuestas, pregunta de forma inteligente o si no, pregunta lo que quieras que yo contestaré lo que me dé la gana.
  #21 (permalink)  
Antiguo 19/03/2008, 14:45
 
Fecha de Ingreso: enero-2008
Mensajes: 203
Antigüedad: 16 años, 3 meses
Puntos: 1
Re: Problemas con JavaMail (auntetificacion)

hola genco, lo que estas escribiendo ees para un foro el cual tenia un año sin recibir nuevos mensajes...

  #22 (permalink)  
Antiguo 19/03/2008, 15:31
Avatar de genco  
Fecha de Ingreso: febrero-2008
Mensajes: 9
Antigüedad: 16 años, 3 meses
Puntos: 0
Re: Problemas con JavaMail (auntetificacion)

jajajajjaja disculpa no soy muy bueno con esto de los foros plop !
Cita:
Iniciado por ericaadbr Ver Mensaje
hola genco, lo que estas escribiendo ees para un foro el cual tenia un año sin recibir nuevos mensajes...

  #23 (permalink)  
Antiguo 18/06/2010, 16:22
 
Fecha de Ingreso: septiembre-2007
Mensajes: 27
Antigüedad: 16 años, 7 meses
Puntos: 0
Respuesta: Problemas con JavaMail (auntetificacion)

Al ultimo codigo hay que agregarle esto.

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.port", "465");

El props.put("mail.smtps.port", "465"); no va tiene que solo estar el props.put("mail.smtp.port", "465");

Esta linea esta mal
SMTPTransport t =
(SMTPTransport)session.getTransport(ssl ? "smtps" : "smtp"); //si ssl=true, smtps si no smtp

Debe ser reemplazada por esta

SMTPTransport t =
(SMTPTransport)session.getTransport("smtp");

Con eso funciona.
Se que lleva mucho tiempo el Post pero los que necesitan la solucion con esto les basta.
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 04:58.