Link to home
Start Free TrialLog in
Avatar of grexx
grexx

asked on

JavaMail: javax.mail.AuthenticationFailedException

I'm having troubles getting JavaMail to work with authentication, using an outside SMTP-server. The server is not the server of my ISP (the one which connects me to the internet now). I can use this SMTP-server to send mails with Thunderbird, so the connection should work.

I get the following error:

javax.mail.AuthenticationFailedException
      at javax.mail.Service.connect(Service.java:306)
      at javax.mail.Service.connect(Service.java:156)
      at javax.mail.Service.connect(Service.java:105)
      at javax.mail.Transport.send0(Transport.java:168)
      at javax.mail.Transport.send(Transport.java:98)
      at net.grexx.square.mail.SimpleSender.send(SimpleSender.java:66)
      at net.grexx.square.mail.ProcessSqlMail.process(ProcessSqlMail.java:67)
      at org.apache.jsp.SimpleSender.test_002ddb_jsp._jspService(org.apache.jsp.SimpleSender.test_002ddb_jsp:46)
      at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
      at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325)
      at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
      at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:245)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:825)
      at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:731)
      at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:526)
      at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
      at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
      at java.lang.Thread.run(Unknown Source)

The java code that sends the mail is:

      public static void send(String smtpServer, String smtpUsername, String smtpPassword, String to, String from
                  , String subject, String body)
      {
            try
            {
                  Properties props = System.getProperties();
                  // -- Attaching to default Session, or we could start a new one --
                  props.put("mail.smtp.host", smtpServer);
                  props.put("mail.smtp.auth", "true");
                  Session session = Session.getDefaultInstance(props, null);
                  // -- Create a new message --
                  Message msg = new MimeMessage(session);
                  // -- Set the FROM and TO fields --
                  msg.setFrom(new InternetAddress(from));
                  msg.setRecipients(Message.RecipientType.TO,
                  InternetAddress.parse(to, false));
                  // -- We could include CC recipients too --
                  // if (cc != null)
                  // msg.setRecipients(Message.RecipientType.CC
                  // ,InternetAddress.parse(cc, false));
                  // -- Set the subject and body text --
                  msg.setSubject(subject);
                  msg.setText(body);
                  // -- Set some other header information --
                  msg.setHeader("X-Mailer", "GrexxBoxxEmail");
                  msg.setSentDate(new Date());
                  
                  Transport tr = session.getTransport("smtp");
                  tr.connect(smtpServer, smtpUsername, smtpPassword);
                  msg.saveChanges();      // don't forget this
                  
                  // -- Send the message --
                  Transport.send(msg);
                  System.out.println("Message sent OK.");
            }
            catch (Exception ex)
            {
                  ex.printStackTrace();
            }
      }

I have no idea what I'm doing wrong here. Any suggestions?
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Are you sure that:

a. you have reproduced the connection details of the Thunderbird account?
b. you are sending to the same sort of address with each?
Avatar of grexx
grexx

ASKER

Yes. To be sure I just did another test. Both use exactly the same settings, send from and to the same address.
CEHJ is probably right, there is a mismatch between your Thunderbird setting and the Java code you're using.

Try watching the mail server debug messages with:
session.setDebug(true)

Try setting mail.smtp.auth to false, but leave the user name and password in the tr.connect.  You might be mistaken about the authentication method.  Having the authenticated user will still work.  There are several types of authenticated use of mail servers, and useAuth might not be true for your mail server, although it requires user login to send email.
Avatar of grexx

ASKER

When I remove the mail.smtp.auth line, the connection seems to work. So I think this solves this part.

When mail is sent to an addres inside the smpt-domain, it works. When the mail is sent to e.g. gmail.com, it doesn't work. Then I get a relay error, while this gives no problem using Thunderbird. This was in fact the reason I added the mail.smtp.auth line. I thought that the relay was refused because authentication wasn't happening.

com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <joe@gmail.com>... Relaying denied. IP name possibly forged [12.34.56.78]
>>When mail is sent to an addres inside the smpt-domain, it works.

That's normal. Relaying will usually require auth
ASKER CERTIFIED SOLUTION
Avatar of mrcoffee365
mrcoffee365
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial


 Hi

 yes i can send mail without using any authentication code when i use the localhost instead of the my own smtp server
after i did install the free smtp software on my machine .

now i have made the following changes in the code as per what u said

here is my changed code

package mailandbean;
import javax.mail.*;          //JavaMail packages
import javax.mail.internet.*; //JavaMail Internet packages
import java.util.*;           //Java Util packages
import javax. mail.Authenticator.*;
import javax.mail.PasswordAuthentication;

public class SendMailBean {


  public String send(String p_from,String p_to,String p_cc,String p_bcc,String p_subject,String p_message,String p_smtpServer) {
    String l_result = "<BR><BR><BR><BR><BR><BR><BR>";
    // Name of the Host machine where the SMTP server is running
    String l_host = p_smtpServer;
    // Gets the System properties
    Properties props = System.getProperties();

    //user authentication
    javax.mail.Authenticator authenticator = new DefaultAuthenticator("username","passowrd");// here i put my username d password for the server access
  // props.put("mail.smtp.host","mail.moonmotors.co.nz");
      props.put("mail.smtp.host",l_host);
   props.put("mail.smtp.auth", "true");
   Session sesion = Session.getInstance(props, authenticator);
    // Puts the SMTP server name to properties object

    props.put("mail.smtp.auth","true");

    // Get the default Session using Properties Object
    Session l_session = Session.getDefaultInstance(props,null);

    l_session.setDebug(true); // Enable the debug mode

    try {
      MimeMessage l_msg = new MimeMessage(l_session); // Create a New message

      l_msg.setFrom(new InternetAddress(p_from)); // Set the From address

      // Setting the "To recipients" addresses
      l_msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(p_to,false));

      // Setting the "Cc recipients" addresses
      l_msg.setRecipients(Message.RecipientType.CC,InternetAddress.parse(p_cc,false));

      // Setting the "BCc recipients" addresses

      l_msg.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(p_bcc,false));

      l_msg.setSubject(p_subject); // Sets the Subject

      // Create and fill the first message part
      MimeBodyPart l_mbp = new MimeBodyPart();
      l_mbp.setText(p_message);

      // Create the Multipart and its parts to it
      Multipart l_mp = new MimeMultipart();
      l_mp.addBodyPart(l_mbp);


      // Add the Multipart to the message
      l_msg.setContent(l_mp);

      // Set the Date: header
      l_msg.setSentDate(new Date());

      // Send the message
      Transport.send(l_msg);
      // If here,then message is successfully sent.
      // Display Success message
      l_result = l_result + "<FONT SIZE=4 COLOR=\"blue\"><B>Success!</B>"+
                 "<FONT SIZE=4 COLOR=\"black\"> "+

                 "<HR><FONT color=green><B>Mail was successfully sent to </B></FONT>: "+p_to+"<BR>";
      //if CCed then,add html for displaying info
      if (!p_cc.equals(""))
        l_result = l_result +"<FONT color=green><B>CCed To </B></FONT>: "+p_cc+"<BR>";
      //if BCCed then,add html for displaying info
      if (!p_bcc.equals(""))
        l_result = l_result +"<FONT color=green><B>BCCed To </B></FONT>: "+p_bcc ;

      l_result = l_result+"<BR><HR>";
    } catch (MessagingException mex) { // Trap the MessagingException Error
        // If here,then error in sending Mail. Display Error message.
        l_result = l_result + "<FONT SIZE=4 COLOR=\"blue\"> <B>Error : </B><BR><HR> "+
                   "<FONT SIZE=3 COLOR=\"black\">"+mex.toString()+"<BR><HR>";
    } catch (Exception e) {

        // If here,then error in sending Mail. Display Error message.
        l_result = l_result + "<FONT SIZE=4 COLOR=\"blue\"> <B>Error : </B><BR><HR> "+
                   "<FONT SIZE=3 COLOR=\"black\">"+e.toString()+"<BR><HR>";

        e.printStackTrace();
    }//end catch block
    finally {
      return l_result;
    }
  } // end of method send
/**
* This is a very simple authentication object that can be used for any
* transport needing basic userName and password type authentication.
*
* @author <a href="mailto:quintonm@bellsouth.net">Quinton McCombs</a>
* @version $Id: DefaultAuthenticator.java,v 1.3 2004/02/19 22:38:07 scolebourne Exp $
*/
public class DefaultAuthenticator extends Authenticator
{
  /** Stores the login information for authentication */
  private PasswordAuthentication authentication;

  /**
   * Default constructor
   *
   * @param userName user name to use when authentication is requested
   * @param password password to use when authentication is requested
   */
  public DefaultAuthenticator(String userName, String password)
  {
      this.authentication = new PasswordAuthentication(
              userName, password );
  }

  /**
   * Gets the authentication object that will be used to login to the mail
   * server.
   *
   * @return A <code>PasswordAuthentication</code> object containing the
   *         login information.
   */
  protected PasswordAuthentication getPasswordAuthentication()
  {
      return this.authentication;
  }
}


} //end of bean


now i get the below error

Error :

--------------------------------------------------------------------------------
javax.mail.SendFailedException: Sending failed; nested exception is: class javax.mail.AuthenticationFailedException

--------------------------------------------------------------------------------
Compose Mail