Hi i didnt find anything about this here on the forum and i cant figure out how to do it myselfe either. i have a homepage runing java with servlets and jsp pages and i want a simple contactform that sends a message from the form to a specific mail. like this:

<form action="contact" method="post">
    <p>Your email address: <input name="email">
    <p>Mail subject: <input name="subject">
    <p>Mail message: <textarea name="message"></textarea>
    <p><input type="submit">
</form>

my question is how to create a servlet that uses the form above to send a message given by the user to my email. please help!

Use String message = request.getParameter("message"); on the servlet to extract each input field value, the following snippet will do the rest:

import java.io.IOException;
import java.util.Properties;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;

public class ContactServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		
		String email = request.getParameter("email");
		String subject = request.getParameter("subject");
		String message = request.getParameter("message");
		
		if(!message.equals(null)){
			Properties props = new Properties();
	        	Session session = Session.getDefaultInstance(props, null);
			
		try {
	                Message m = new MimeMessage(session);
	                m.setFrom(new InternetAddress(email, "user"));
	                m.addRecipient(Message.RecipientType.TO, new InternetAddress("dest@example.com", "me"));
	                m.setSubject(subject);
	                m.setText(message);
	                Transport.send(m);

	        } catch (AddressException e) {
	        	e.printStackTrace();
	        } catch (javax.mail.MessagingException e) {
		        e.printStackTrace();
		}
	        
		RequestDispatcher view = request.getRequestDispatcher("success.jsp");
			
		view.forward(request, response);

		}
	}

}

thank you but that didnt work, i didnt recive any message when using it, please help! i think i need something were i can specify my smtp and other settings too. also i didnt understand exactly what you meaned with this "Use String message = request.getParameter("message"); on the servlet to extract each input field value,"

That's weird, works flawlessly in my computer. In most cases, you need to configure Postfix or Sendmail to accept incoming email through port 25.

That's weird, works flawlessly in my computer. In most cases, you need to configure Postfix or Sendmail to accept incoming email through port 25.

hmm okay how do i do that? and can you please tell me what i should change in that servlet? i would love to have a short guide or something maby i did something wrong.

Maby it is worth to say that im not using my own smtp server. i have a domain name and i got a free emailservice from that company

Can you give the complete stack trace of the error?

Yes, a SMTP server is missing according to the first line.

Got it working now! thanks so much man! love you!

Another alternative, is to use Gmail as mail transport agent, with some modifications of the code:

import java.io.IOException;
import java.util.Properties;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;

public class ContactServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		
		String email = request.getParameter("email");
		String subject = request.getParameter("subject");
		String message = request.getParameter("message");
		
		if(!message.equals(null)){
			String host = "smtp.gmail.com";
	    	int port = 587;
	    	String username = "*** your Gmail username ***";
	    	String password = "*** your Gmail password ***";
	    	
			Properties props = new Properties();
			props.put("mail.smtp.auth", "true");
	    	props.put("mail.smtp.starttls.enable", "true");
	        Session session = Session.getDefaultInstance(props, null);
			
	        String body = message;
	        
		try {
	        	Message m = new MimeMessage(session);
	        	m.setFrom(new InternetAddress(email, null));
	        	m.addRecipient(Message.RecipientType.TO, new InternetAddress("destination@example.com", "me"));
	        	m.setSubject(subject);
	        	m.setText(body);
	            
	        	Transport transport = session.getTransport("smtp");
	    		transport.connect(host, port, username, password);
	     
	    		Transport.send(m);

	        } catch (AddressException e) {
	        	e.printStackTrace();
	        } catch (javax.mail.MessagingException e) {
				e.printStackTrace();
			}
	        
			RequestDispatcher view = request.getRequestDispatcher("success.jsp");
			
			view.forward(request, response);

		}
	}

}

Yes, a SMTP server is missing according to the first line.

ive got it working now but i would be nice if i had a validator for the mail and message. how to add this?

Well, we're validating if the message is null. It's possible to add more fields on that condition and an else clause to redirect to the form again. Also, would be nice to pass a request parameter to the jsp.

import java.io.IOException;
import java.util.Properties;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;

public class ContactServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		
		String email = request.getParameter("email");
		String subject = request.getParameter("subject");
		String message = request.getParameter("message");
		
		if(!message.isEmpty()){
			String host = "smtp.gmail.com";
	    		int port = 587;
	    		String username = "*** your Gmail username ***";
	    		String password = "*** your Gmail password ***";
	    	
			Properties props = new Properties();
			props.put("mail.smtp.auth", "true");
	    		props.put("mail.smtp.starttls.enable", "true");
	        	Session session = Session.getDefaultInstance(props, null);
			
	        	String body = message;
	        
			try {
	         		Message m = new MimeMessage(session);
	       			m.setFrom(new InternetAddress(email, null));
	        		m.addRecipient(Message.RecipientType.TO, new InternetAddress("destination@example.com", "me"));
	        		m.setSubject(subject);
	          		m.setText(body);
	            
	          		Transport transport = session.getTransport("smtp");
	    	  		transport.connect(host, port, username, password);
	     
	    	 		Transport.send(m);

	        	} catch (AddressException e) {
	        		e.printStackTrace();
	        	} catch (javax.mail.MessagingException e) {
				e.printStackTrace();
			}
	        
			RequestDispatcher view = request.getRequestDispatcher("success.jsp");
			view.forward(request, response);

		}else{
			request.setAttribute("error", "Message is empty");
			
			RequestDispatcher view = request.getRequestDispatcher("contact.jsp");  // return to contact form
			view.forward(request, response);
			
		}
	}

}

Use out.println(request.getAttribute("error")) on the contact form to show the error. A better alternative would be:

<p>Mail message: <textarea name="message"></textarea>
<% if (request.getAttribute("error") != null) out.println(request.getAttribute("error")); %></p>

Hmm im using this code how i i made the changes here? for email vaildation and message validation

import java.io.IOException;
import java.util.Properties;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;

public class ContactServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		
		String email = request.getParameter("email");
		String subject = request.getParameter("subject");
		String message = request.getParameter("message");
		
		if(!message.equals(null)){
			Properties props = new Properties();
			props.put("mail.smtp.host", "mysmptserver.com");
			props.put("mail.smtp.port", "587");
			
	        	Session session = Session.getDefaultInstance(props, null);
			
		try {
	                Message m = new MimeMessage(session);
	                m.setFrom(new InternetAddress(email, ""));
	                m.addRecipient(Message.RecipientType.TO, new InternetAddress("myadress@mydomain.com", ""));
	                m.setSubject(subject);
	                m.setText(message);
	                Transport.send(m);

	        } catch (AddressException e) {
	        	e.printStackTrace();
	        } catch (javax.mail.MessagingException e) {
		        e.printStackTrace();
		}
	        
		RequestDispatcher view = request.getRequestDispatcher("success.jsp");
			
		view.forward(request, response);

		}
	}

}

Both are almost the same code...

String email = request.getParameter("email");
	String subject = request.getParameter("subject");
	String message = request.getParameter("message");
		
	if (email.isEmpty()){
		request.setAttribute("err_email", "Email is empty");
	}
	if (message.isEmpty()){
		request.setAttribute("err_msg", "Message is empty");
	}

	if(!email.isEmpty() && !message.isEmpty()){
	...
	}else{
		RequestDispatcher view = request.getRequestDispatcher("contact.jsp");
			
		view.forward(request, response);
			
	}

It didnt work, just got a plain white text on error.

Could you be more specific? Are you using out.println(request.getAttribute("err_msg")) on the contact form?

Sorry for the bad information, ive got i working with message and mail but itried this with the subject but it didnt work to compile it!.

package net.sourceforge.subsonic.controller;

import java.io.IOException;
import java.util.Properties;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;

public class ContactServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		
	String email = request.getParameter("email");
	String subject = request.getParameter("subject");
	String message = request.getParameter("message");
		
	if (email.isEmpty()){
		request.setAttribute("err_email", "Email is empty");
	}else if (message.isEmpty()){
		request.setAttribute("err_msg", "Message is empty");
	}else if (subject.isEmpty()){
		request.setAttribute("err_sub", "subject is empty");
	}

	
		
		if(!email.isEmpty() && !message.isEmpty()) && !subject.isEmpty()){
			Properties props = new Properties();
			props.put("mail.smtp.host", "mysmptserver.com");
			props.put("mail.smtp.port", "587");
			
	        	Session session = Session.getDefaultInstance(props, null);
			
		try {
	                Message m = new MimeMessage(session);
	                m.setFrom(new InternetAddress(email, ""));
	                m.addRecipient(Message.RecipientType.TO, new InternetAddress("myadress@mydomain.com", ""));
	                m.setSubject(subject);
	                m.setText(message);
	                Transport.send(m);

	        } catch (AddressException e) {
	        	e.printStackTrace();
	        } catch (javax.mail.MessagingException e) {
		        e.printStackTrace();
		}
	        
		RequestDispatcher view = request.getRequestDispatcher("donate.view");
			
		view.forward(request, response);
		
			}else{
		RequestDispatcher view = request.getRequestDispatcher("help.view");
			
		view.forward(request, response);
			

		}
	}

}

There is an extra parenthesis on message.isEmpty() call.

if(!email.isEmpty() && !message.isEmpty()) && !subject.isEmpty()){

There is an extra parenthesis on message.isEmpty() call.

if(!email.isEmpty() && !message.isEmpty()) && !subject.isEmpty()){

Thanks man! I really appreciate your help! i have one more thing to ask about, now i can write whatever i want in the emailform i would be nice to have som vaildator for a real email so you have to write exampel@example.com instead of just thisismyemailgofish

That's more difficult, you need a static method that does an email extraction using regular expressions (Regex) and return a boolean.

Just another suggestion, you can also store the values of each field on request parameters and pass it to each input field to remember the content.

That's more difficult, you need a static method that does an email extraction using regular expressions (Regex) and return a boolean.

Just another suggestion, you can also store the values of each field on request parameters and pass it to each input field to remember the content.

Okay you know how to do it? otherwise i think i can do sometihng with javascript!
yeah i just got that on my mind how do i do that? haha :) hmm i tried to change so a text like "Your message has been sent!" appears instead of a new page, this would be nice also

Here is the example, use it into a conditional. I extracted the pattern from http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/

public static boolean test(String str){
		String reg = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
		Pattern p = Pattern.compile(reg);
		Matcher m = p.matcher(str);
		while(m.find())
		{
			String s1 = m.group(0);
			if (str == s1) return true;
		}

		return false;
	}

Here is the example, use it into a conditional. I extracted the pattern from http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/

public static boolean test(String str){
		String reg = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
		Pattern p = Pattern.compile(reg);
		Matcher m = p.matcher(str);
		while(m.find())
		{
			String s1 = m.group(0);
			if (str == s1) return true;
		}

		return false;
	}

Cant compile that one, dunno how to implement it to the code!

I forgot the i letter on line 8. Place that method after doGet. Use the following conditional after email.isEmpty() condition.

if (!test(email)){
		request.setAttribute("err_email", "Provided incorrect email");
	}

I forgot the i letter on line 8. Place that method after doGet. Use the following conditional after email.isEmpty() condition.

if (!test(email)){
		request.setAttribute("err_email", "Provided incorrect email");
	}

okay i this what you mean because i couldnt compile it.

import java.io.IOException;
import java.util.Properties;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;

public class ContactServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
	
	public static boolean test(String str){
		String reg = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
		Pattern p = Pattern.compile(reg);
		Matcher m = p.matcher(str);
		while(m.find())
		{
			String s1 = m.group(0);
			if (str == s1) return true;
		}

		return false;
	}
		
	String email = request.getParameter("email");
	String subject = request.getParameter("subject");
	String message = request.getParameter("message");
		
	if (email.isEmpty()){
		if (!test(email)){
		request.setAttribute("err_email", "Provided incorrect email");
	}
		request.setAttribute("err_email", "Please proivde a email");
	}else if (message.isEmpty()){
		request.setAttribute("err_msg", "Please provide a message");
	}else if (subject.isEmpty()){
		request.setAttribute("err_sub", "Please provide a subject");
	}
	
		
		if(!email.isEmpty() && !message.isEmpty() && !subject.isEmpty()){
			Properties props = new Properties();
			props.put("mail.smtp.host", "mysmptserver.com");
			props.put("mail.smtp.port", "587");
			
	        	Session session = Session.getDefaultInstance(props, null);
			
		try {
	                Message m = new MimeMessage(session);
	                m.setFrom(new InternetAddress(email, ""));
	                m.addRecipient(Message.RecipientType.TO, new InternetAddress("myadress@mydomain.com", ""));
	                m.setSubject(subject);
	                m.setText(message);
	                Transport.send(m);

	        } catch (AddressException e) {
	        	e.printStackTrace();
	        } catch (javax.mail.MessagingException e) {
		        e.printStackTrace();
		}
	        
		RequestDispatcher view = request.getRequestDispatcher("donate.view");
			
		view.forward(request, response);
		
			}else{
		RequestDispatcher view = request.getRequestDispatcher("help.view");
			
		view.forward(request, response);
			
			

		}
	}

}

There is missing two imports. Place the methods aside, not inside.

package net.sourceforge.subsonic.controller;

import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;

public class ContactServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
	
		
	String email = request.getParameter("email");
	String subject = request.getParameter("subject");
	String message = request.getParameter("message");
		
	if (email.isEmpty()){
		request.setAttribute("err_email", "Please proivde a email");
	}
	if (!test(email)){
		request.setAttribute("err_email", "Provided incorrect email");
	}
	if (message.isEmpty()){
		request.setAttribute("err_msg", "Please provide a message");
	}
	if (subject.isEmpty()){
		request.setAttribute("err_sub", "Please provide a subject");
	}
	
		
		if(!email.isEmpty() && !message.isEmpty() && !subject.isEmpty()){
			Properties props = new Properties();
			props.put("mail.smtp.host", "mysmptserver.com");
			props.put("mail.smtp.port", "587");
			
	        	Session session = Session.getDefaultInstance(props, null);
			
		try {
	                Message m = new MimeMessage(session);
	                m.setFrom(new InternetAddress(email, ""));
	                m.addRecipient(Message.RecipientType.TO, new InternetAddress("myadress@mydomain.com", ""));
	                m.setSubject(subject);
	                m.setText(message);
	                Transport.send(m);

	        } catch (AddressException e) {
	        	e.printStackTrace();
	        } catch (javax.mail.MessagingException e) {
		        e.printStackTrace();
		}
	        
		RequestDispatcher view = request.getRequestDispatcher("donate.view");
			
		view.forward(request, response);
		
			}else{
		RequestDispatcher view = request.getRequestDispatcher("help.view");
			
		view.forward(request, response);
			
			

		}
	}
	public static boolean test(String str){
		String reg = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
		Pattern p = Pattern.compile(reg);
		Matcher m = p.matcher(str);
		while(m.find())
		{
			String s1 = m.group(0);
			if (str == s1) return true;
		}

		return false;
	}

}
package net.sourceforge.subsonic.controller;

import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;

public class ContactServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
	
		
	String email = request.getParameter("email");
	String subject = request.getParameter("subject");
	String message = request.getParameter("message");
		
	if (email.isEmpty()){
		request.setAttribute("err_email", "Please proivde a email");
	}
	if (!test(email)){
		request.setAttribute("err_email", "Provided incorrect email");
	}
	if (message.isEmpty()){
		request.setAttribute("err_msg", "Please provide a message");
	}
	if (subject.isEmpty()){
		request.setAttribute("err_sub", "Please provide a subject");
	}
	
		
		if(!email.isEmpty() && !message.isEmpty() && !subject.isEmpty()){
			Properties props = new Properties();
			props.put("mail.smtp.host", "mysmptserver.com");
			props.put("mail.smtp.port", "587");
			
	        	Session session = Session.getDefaultInstance(props, null);
			
		try {
	                Message m = new MimeMessage(session);
	                m.setFrom(new InternetAddress(email, ""));
	                m.addRecipient(Message.RecipientType.TO, new InternetAddress("myadress@mydomain.com", ""));
	                m.setSubject(subject);
	                m.setText(message);
	                Transport.send(m);

	        } catch (AddressException e) {
	        	e.printStackTrace();
	        } catch (javax.mail.MessagingException e) {
		        e.printStackTrace();
		}
	        
		RequestDispatcher view = request.getRequestDispatcher("donate.view");
			
		view.forward(request, response);
		
			}else{
		RequestDispatcher view = request.getRequestDispatcher("help.view");
			
		view.forward(request, response);
			
			

		}
	}
	public static boolean test(String str){
		String reg = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
		Pattern p = Pattern.compile(reg);
		Matcher m = p.matcher(str);
		while(m.find())
		{
			String s1 = m.group(0);
			if (str == s1) return true;
		}

		return false;
	}

}

i compiled that one and tryied it but it didnt work for me i could send a message with just a name like Tom. is there any way to save the information in each field?

To save the information of each field use request.setAttribute("emailState", email) and then out.println(request.getAttribute("emailState")) on the input value (contact form), very similar to the procedure to pass errors.

To save the information of each field use request.setAttribute("emailState", email) and then out.println(request.getAttribute("emailState")) on the input value (contact form), very similar to the procedure to pass errors.

hmm where do i enter this? tried on several places now but cant figure it out. i also still can send message with wrong mailadress :(

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.