aspose file tools*
The moose likes Servlets and the fly likes Getting exception in sending Email from Servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Getting exception in sending Email from Servlet" Watch "Getting exception in sending Email from Servlet" New topic
Author

Getting exception in sending Email from Servlet

Mishaal Khan
Ranch Hand

Joined: Aug 21, 2008
Posts: 61
I have the following code to send an email from a servlet.Servlet read mail parameters from an
html file and then sends email ,but getting error i.e java.lang.NoClassDefFoundError: javax/mail/Address

Following is the servlet code and Exception its generating :

SERVLET CODE :
-------------------

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.InternetAddress;
import javax.mail.event.*;
import java.net.*;
import java.util.*;

public class mailservlet extends HttpServlet

{

public void doPost(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException

{

PrintWriter out=response.getWriter();

response.setContentType("text/html");

try

{

Properties props=new Properties();

props.put("mail.smtp.host","localhost"); // 'localhost' for testing

Session session1 = Session.getDefaultInstance(props,null);

String s1 = request.getParameter("from"); //sender (from)

String s2 = request.getParameter("to");

String s3 = request.getParameter("subject");

String s4 = request.getParameter("message");

MimeMessage message =new MimeMessage(session1);

message.setFrom(new InternetAddress(s1));

message.addRecipient(Message.RecipientType.TO,new InternetAddress(s2) );
message.setSubject(s3);

message.setText(s4);

Transport.send(message);

out.println("mail has been sent");

}

catch(Exception ex)

{

System.out.println("ERROR....."+ex);

}

}

}



EXCEPTION :
--------------

SEVERE: Allocate exception for servlet mailservlet
java.lang.NoClassDefFoundError: javax/mail/Address
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2328)
at java.lang.Class.getConstructor0(Class.java:2640)
at java.lang.Class.newInstance0(Class.java:321)
at java.lang.Class.newInstance(Class.java:303)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1089)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:791)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:127)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:595)
4-Mar-2009 4:44:45 PM org.apache.catalina.core.StandardWrapperValve invoke
INFO: Servlet mailservlet is currently unavailable
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39568
    
  27
You need the JavaMail and Java Activation Framework jar files in your classpath (which, for a servlet, would be the WEB-INF/lib directory). They are named something like mail-1.4.2.jar and
activation-1.1.1.jar.


Ping & DNS - updated with new look and Ping home screen widget
nilesh beit
Greenhorn

Joined: Feb 04, 2009
Posts: 13
Hey
try this code
Its working correctly

Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39568
    
  27
nilesh beit wrote:Hey
try this code
Its working correctly

How does different code help with a NoClassDefFoundError?
Mishaal Khan
Ranch Hand

Joined: Aug 21, 2008
Posts: 61
Thank you very much for both replies.

I 'll start with Ulf response :

I am using MyEclipse for this project and these 2 files you recommended are already included in Java build path
in J2EE 1.4 Library Container.when I try to add them as External JAR files it is giving warning that files are already included.
Do you still recommend to add it ?

Nilesh response :

1 ) Your code definetly must be working and a very good reference and start for me to learn about Java Mail API , but I want to give a try to code in my servlet,just wondering is there anything missing or wrong in my code?

2) As I have get this code from some tutorial ,just curious about 2nd argument of Properties i.e


props.put("mail.smtp.host","localhost");

what should be the value in 2nd argument if I don't know about host,as in my case I am getting both email addresses (to and from ) through an
html page!

Thanks.





Kuldeep Tewari
Ranch Hand

Joined: May 22, 2006
Posts: 35
Mishaal Khan wrote:
what should be the value in 2nd argument if I don't know about host

You ought to have a SMTP host for sending email.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39568
    
  27
Mishaal Khan wrote:TI am using MyEclipse for this project and these 2 files you recommended are already included in Java build path
in J2EE 1.4 Library Container.when I try to add them as External JAR files it is giving warning that files are already included.
Do you still recommend to add it ?

"NoClassDefFoundError" does not occur at build time, so whatever you do with the build path is irrelevant. You need to add those libraries to the classpath used at runtime.

Your code definetly must be working

Why? Changing the code does nothing to resolve a NoClassDefFoundError - it's a classpath issue.

props.put("mail.smtp.host","localhost");
what should be the value in 2nd argument ?

That's the server name of your email server. "localhost" is correct only if you have a mail server running on your machine.
Mishaal Khan
Ranch Hand

Joined: Aug 21, 2008
Posts: 61
Ulf,

I added the jars in lib files and that particular problem is solved.Thanks. But have another problem.

I assume from your reply that 2nd argument for Properties should be host email server,so if I am expecting
a mail on hotmail account it should be "smtp.hotmail.com" ? Code that Nilesh posted also has 2nd
argument as "smtp.gmail.com".

I did the same ,but having exception :



ERROR.....javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: Unknown SMTP host: smtp.hotmail.com;
nested exception is:
java.net.UnknownHostException: smtp.hotmail.com

Whats wrong am I doing?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39568
    
  27
I don't know if HotMail's server can be used like this, and if it can, whether that's the correct address to use. You should use the mail server of your ISP (or your company's mail server); you can find its host name or address in the settings of your email client.
nilesh beit
Greenhorn

Joined: Feb 04, 2009
Posts: 13
Hey

I found two links which indicate that it may not possible with smtp.hotmail.com

1. Search term hotmail in http://java.sun.com/products/javamail/FAQ.html

2. http://www.emailaddressmanager.com/tips/mail-settings.html
this link says "Hotmail is using the HTTP protocol for connecting you to your mailbox."

Try sending with gmail first just to check whether setup is rigtht. Check you have setup everything as Ulf suggested. And then find ways for hotmail

Regards
Mishaal Khan
Ranch Hand

Joined: Aug 21, 2008
Posts: 61
Nilesh,

I change my code according to your code with only difference as I have defined SMTPAuthenticator class not as inner class but as seperate class.I have
hardcoded the userid and password inside the class.

And also instead of

Authenticator auth = new SMTPAuthenticator() , I have instantiate this class as:

SMTPAuthenticator auth = new SMTPAuthenticator(), because on defining Authenticator auth = new SMTPAuthenticator(), its giving error 'type Authenticator is ambiguos'
so I instantiate it as SMTPAuthenticator auth = new SMTPAuthenticator();

but getting this exception :


ERROR.....javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect


CODE FOR MY SERVLET :

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.InternetAddress;
import javax.mail.event.*;
import java.net.*;
import java.util.*;


public class mailservlet extends HttpServlet

{

public void doPost(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException

{

PrintWriter out=response.getWriter();

response.setContentType("text/html");

try

{

Properties props=new Properties();

props.put("mail.smtp.host","smtp.gmail.com");

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

SMTPAuthenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);


String s1 = request.getParameter("from"); //sender (from)

String s2 = request.getParameter("to");

String s3 = request.getParameter("subject");

String s4 = request.getParameter("msg");

MimeMessage message =new MimeMessage(session);

message.setFrom(new InternetAddress(s1));

message.addRecipient(Message.RecipientType.TO,new InternetAddress(s2) );
message.setSubject(s3);

message.setText(s4);

Transport.send(message);

out.println("mail has been sent");

}

catch(Exception ex)

{

System.out.println("ERROR....."+ex);

}

}

}

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60071
    
  65

Please be sure to use code tags when posting code to the forums. Unformatted code is extremely hard to read and many people that might be able to help you will just move along to posts that are easier to read. Please read this for more information.

You can go back and change your post to add code tags by clicking the button on your post.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Bauke Scholtz
Ranch Hand

Joined: Oct 08, 2006
Posts: 2458
Mishaal Khan wrote:
class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect


Either the hostname and/or port is wrong, or there's a hardware/software firewall or router blocking the connection.
Mishaal Khan
Ranch Hand

Joined: Aug 21, 2008
Posts: 61
Host name is working fine with another example above (Nilesh Biet) code.
I did not specify any port no in my code,it is giving port no in exception message!

Thanks.

Bauke Scholtz
Ranch Hand

Joined: Oct 08, 2006
Posts: 2458
I was just translating the exception message into easy-to-understand words for newbies. It's up to you to find out the root cause of the problem. Which thus can be a wrong hostname/port or a blocking firewall/router.
nilesh beit
Greenhorn

Joined: Feb 04, 2009
Posts: 13
SMTPAuthenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);

This might be causing problem
You said you have created new class SMTPAuthenticator , but have you extended it from javax.mail.Authenticator . That is required.
This line should be

The class Authenticator represents an object that knows how to obtain authentication for a network connection.
Applications use this class by creating a subclass, and registering an instance of that subclass with the session when it is created.
When authentication is required, the system will invoke a method on the subclass (like getPasswordAuthentication)
Mishaal Khan
Ranch Hand

Joined: Aug 21, 2008
Posts: 61
Thanks for the reply.

When I dedfined

Authenticator auth = new SMTPAuthenticator(), its giving error 'type Authenticator is ambiguos'

then I changed it to SMTPAuthenticator auth = new SMTPAuthenticator(),
and the error was gone,but the application is not working as required. You have any idea why it is giving
this error 'type Authenticator is ambiguos' ?And Yes I have extended javax.mail.Authenticator in my class.

Thanks.
Mishaal Khan
Ranch Hand

Joined: Aug 21, 2008
Posts: 61
OK, the error 'type Authenticator is ambiguos ' is gone when I imported

javax.mail.Authenticator as a seperate statement , although I already had import javax.mail.* statement in my servlet.
so this problem is solved.But still getting exception


ERROR.....javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect

Bauke Scholtz
Ranch Hand

Joined: Oct 08, 2006
Posts: 2458
When I dedfined

Authenticator auth = new SMTPAuthenticator(), its giving error 'type Authenticator is ambiguos'

You have more than one class with the name "Authenticator" in the same classpath scope (imported packages and the current package). The compiler can't determine based on the coding which one to use and is thus giving this error. This has nothing to do with your initial problem however.

Edit: OK, you fixed it meanwhile.
Bauke Scholtz
Ranch Hand

Joined: Oct 08, 2006
Posts: 2458
Mishaal Khan wrote:
class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect


The same answer stays: either hostname/port is wrong or a firewall/router is blocking the connection.
Balu Sadhasivam
Ranch Hand

Joined: Jan 01, 2009
Posts: 874


Port no is wrong. Try with 465 or 587
Bauke Scholtz
Ranch Hand

Joined: Oct 08, 2006
Posts: 2458
The answer on the hostname/port number is to be found in the developer documentation of the mail service in question. Go to gmail.com and check it there.

Regarding the firewall/router, you need to check the whole network path if there isn't any software or hardware which acts as a firewall/router and if it is properly configured. It should allow the access to/from the specified hostname/port.
Mishaal Khan
Ranch Hand

Joined: Aug 21, 2008
Posts: 61
Thanks for the replies.

Actually I am not very knowledgeable in networking side ,so don't know how to check or configure the
network path . I have ZoneAlarm installed on my system and I guess its creating this problem.
Would anyone please guide me in checking or configuring settings of firewall or router.

Thanks.

nilesh beit
Greenhorn

Joined: Feb 04, 2009
Posts: 13
Hello
Thats not a zonealarm problem.
Assuming you are directly connecting to internet through broadband\modem and not a firewalled router which is blocking smtp and pop ports.

Add some properties shown below
Mishaal Khan
Ranch Hand

Joined: Aug 21, 2008
Posts: 61
Thaaaaaaank you very much Nilesh.It worked and mail has been sent.

I tried the same example with yahoo.com as its smtp address is smtp.mail.yahoo.com and port is 25 ,but my email address is yahoo.ca
so again having exception Connection time out on port 25.Does it make any difference yahoo.com or yahoo.ca?
Would you please guide how can we get the particular smpt host name ?

Thanks.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18150
    
    8

You get the SMTP host name by asking the owner of the SMTP host. Or by finding online instructions posted by the owner of the host.

If your email address is "something@yahoo.ca" then you will want to use the SMTP host for yahoo.ca to send your e-mails. If you use some other host, then quite likely it will refuse to send your messages. Or if it doesn't, then the recipient's host will quite likely notice that you are using a loose server and will flag them as probable spam. And be prepared to authenticate yourself to that host. If yahoo.ca allows direct access to its SMTP server, you should find instructions on how to do that somewhere on the yahoo.ca site.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Getting exception in sending Email from Servlet
 
Similar Threads
JavaMail
Call a Servlet from JSP
Problem with mail
javamail error
java.lang.ClassNotFoundException: javax.mail.Message