Question

JavaMail: javax.mail.AuthenticationFailedException

Asked by: grexx

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?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-01-15 at 04:49:03ID22122831
Tags

javax.mail.authenticationfailedexception

,

authenticationfailedexception

,

mail

,

javamail

,

javax.mail

Topics

Java Programming Language

,

Java Server Pages (JSP)

,

JavaMail

Participating Experts
3
Points
500
Comments
7

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. JavaMail and Return-Path
    How to set the "Return-Path" value with JavaMail ? I've tried with : //msg is MimeMessage msg.setHeader("Return-Path", "<foo@fee.com>"); Each time I send a mail, it seems the server puts its own value instead.
  2. javamail session Properties
    in my application i use javamail and my session is setup using the props, which is the System properties, will this allow me to send mail to the host like it is or does it need my password and username,if so how do I put them in? what is System.getProperties()? My code at pr...
  3. JavaMail problem
    Hi, I wrote this simple program, compiled them, but when I want to run then he write: Exception in thread "main" java.lang.NoClassDefFoundError: SendMessage import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; ...
  4. JavaMail
    I'm trying to use the JavaMail to send and receive message through my yahoo account which has pop3 and smtp but I keep getting this error: "javax.mail.MessagingException: 530 authentication required ". How do I set this authentication on my code? Below is the code...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: CEHJPosted on 2007-01-15 at 04:49:15ID: 18315845

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?

 

by: grexxPosted on 2007-01-15 at 05:12:37ID: 18315927

Yes. To be sure I just did another test. Both use exactly the same settings, send from and to the same address.

 

by: mrcoffee365Posted on 2007-01-15 at 06:19:07ID: 18316239

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.

 

by: grexxPosted on 2007-01-15 at 08:44:24ID: 18317281

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]

 

by: CEHJPosted on 2007-01-15 at 08:47:02ID: 18317304

>>When mail is sent to an addres inside the smpt-domain, it works.

That's normal. Relaying will usually require auth

 

by: mrcoffee365Posted on 2007-01-15 at 10:41:20ID: 18318087

If you are sending out of the smtp-domain, from a valid user within smtp-domain, then you need to change your authentication code slightly:

            javax.mail.Authenticator authenticator = new org.apache.commons.mail.DefaultAuthenticator(username,userpass);

            props.put("mail.smtp.host", smtpHost);
            props.put("mail.smtp.auth", "true");
                  Session sesion = Session.getInstance(props, authenticator);

You can also write your own DefaultAuthenticator, based on the commons class found here:
http://www.koders.com/java/fid69D36DBE335758C466ADBB35D28D74033185A612.aspx

This is only for the case where your MAIL FROM is on smtpHost and the To is outside the host.

 

by: rauf_patsPosted on 2007-01-26 at 07:51:56ID: 18404967



 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



20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...