O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

20.2. Sending Email from a Servlet

Problem

You want to send emails from a servlet.

Solution

Import the javax.mail and javax.mail.internet packages at the top of the servlet source code. Create a sendMessage( ) method (or a method with a different name) that can be called from the servlet methods doGet( ) or doPost( ).

Discussion

The sendMessage( ) method in Example 20-1 uses the JavaMail API to connect with a mail server, construct an email message, and then send that message to one or more recipients. The servlet obtains the various components of an email—the target email address, the sender's address, the subject field, and the email's body content—from request parameters. The servlet can handle a form submitted by a client using a web browser.

Note

The form tag might look like this:

<form method="POST" action=
"/home/servlet/com.jspservletcookbook.EmailServlet">

Example 20-1 calls the sendMessage( ) method from the service method doPost( ). The sendMessage( ) method parameters comprise the parts of an email: the SMTP server, the recipient of the email (the variable to), the "from" address of the sender, the email subject, and the email's content.

Example 20-1. A servlet sends email based on request parameter values

package com.jspservletcookbook;    

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

import javax.servlet.*;
import javax.servlet.http.*;

public class EmailServlet extends HttpServlet { //default ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required