Edit Edit

Java Servlet FAQ


How do you send e-mail from a servlet?


There are two ways to do it:
1) use the JavaMail API (the preferred way) or
2) use the undocumented class, SmtpClient.

Here is example code that illustrates each method:

1) JavaMail example

// import the JavaMail packages
import javax.mail.*;
import javax.mail.internet.*;

// import the servlet packages
import javax.servlet.*;
import javax.servlet.http.*;

// import misc classes that we need
import java.util.*;
import java.io.*;

public class SendMailServlet extends HttpServlet {
    String smtpServer;

    public void init(ServletConfig config) throws ServletException
    {
        super.init(config);

        // get the SMTP server from the servlet properties
        smtpServer = config.getInitParameter("smtpServer");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
                       throws ServletException, IOException
    {
        // get the message parameters from the HTML page
        String from = req.getParameter("from");
        String to = req.getParameter("to");
        String subject = req.getParameter("subject");
        String text = req.getParameter("text");

        PrintWriter out = res.getWriter();
        res.setContentType("text/html");

        try {
            // set the SMTP host property value
            Properties properties = System.getProperties();
            properties.put("mail.smtp.host", smtpServer);

            // create a JavaMail session
            Session session = Session.getInstance(properties, null);

            // create a new MIME message
            MimeMessage message = new MimeMessage(session);

            // set the from address
            Address fromAddress = new InternetAddress(from);
            message.setFrom(fromAddress);

            // set the to address
            if (to != null) {
                Address[] toAddress = InternetAddress.parse(to);
                message.setRecipients(Message.RecipientType.TO, toAddress);
            }
            else
                throw new MessagingException("No \"To\" address specified");

            // set the subject
            message.setSubject(subject);

            // set the message body
            message.setText(text);

            // send the message
            Transport.send(message);

            out.println("Message sent successfully.");
        }
        catch (AddressException e) {
            out.println("Invalid e-mail address.<br>" + e.getMessage());
        }
        catch (SendFailedException e) {
            out.println("Send failed.<br>" + e.getMessage());
        }
        catch (MessagingException e) {
            out.println("Unexpected error.<br>" + e.getMessage());
        }
    }
}

2) SmtpClient example

// import undocumented SmtpClient class
import sun.net.smtp.SmtpClient;

// import the servlet packages
import javax.servlet.*;
import javax.servlet.http.*;

// import misc classes that we need
import java.util.*;
import java.io.*;

public class SendMailServlet extends HttpServlet {
    String smtpServer;

    public void init(ServletConfig config) throws ServletException
    {
        super.init(config);

        // get the SMTP server from the servlet properties
        smtpServer = config.getInitParameter("smtpServer");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
                       throws ServletException,   IOException
    {
        // get the message parameters from the HTML page
        String from = req.getParameter("from");
        String to = req.getParameter("to");
        String subject = req.getParameter("subject");
        String text = req.getParameter("text");

        PrintWriter out = res.getWriter();
        res.setContentType("text/html");

        try {
            // create an SMTP client
            SmtpClient smtp = new SmtpClient(smtpServer);

            // set the from and to fields
            smtp.from(from);
            smtp.to(to);

            // get the print stream
            PrintStream message = smtp.startMessage();

            // write the message to the print stream
            message.println("From: " + from);
            message.println("To: " + to);
            message.println("Subject: " + subject);
            message.println(text);

            // close the SMTP connection and send the message
            smtp.closeServer();

            out.println("Message sent successfully.");
        }
        catch (IOException e) {
            out.println("Unexpected error.<br>" + e.getMessage());
        }
    }
}

To use the send mail servlet, you need to set the servlet property, smtpServer, to the host name or IP address of your SMTP mail server. Then invoke the mail servlet with the following example HTML:

<HTML>
<BODY>
<FORM ACTION=http://localhost:8080/servlet/SendMailServlet METHOD=post>
<TABLE><TBODY ALIGN=RIGHT>
<TR><TD>From:</TD><TD><INPUT TYPE=TEXT NAME=from SIZE=64></TD></TR>
<TR><TD>To:</TD><TD><INPUT TYPE=TEXT NAME=to SIZE=64></TD></TR>
<TR><TD>Subject:</TD><TD><INPUT TYPE=TEXT NAME=subject SIZE=64></TD></TR>
<TR><TD COLSPAN=2><TEXTAREA NAME=text ROWS=8 COLS=64></TEXTAREA></TD></TR>
<TR><TD><INPUT TYPE=SUBMIT VALUE=SEND></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>



Last updated 01/16/2000 09:14:47 AM