Home

JSP and Beyond

a pragmatic primer on building web-based solutions with Java technologies


Sending Email

Sending email from your JSPs is easy, but requires some configuration. In order to send email from your application you will unfortunately need to add some components to your application. The Java Mail API (http://java.sun.com/products/javamail/) is the most common way to include the toolset to send email. The Java Mail API is accessible via the mail.jar. The latest version of the mail.jar can be downloaded from:
https://maven-repository.dev.java.net/nonav/repository/javax.mail/jars/

Once you have downloaded the jar, it can be placed within the “web-inf/lib” folder within your application server which makes it accessible to any applications running on that application server. The code below will then leverage that information in that jar file to send an email.

<%@ page import=”sun.net.smtp.SmtpClient, java.io.*” %>
<%
String sSender=”youremail@yourhost.com”;
String sRecipient=”reciptient@theirhost.com”;
try{
SmtpClient client = new SmtpClient(”our.mailserver.com”);
client.from(sSender);
client.to(sRecipient);
PrintStream message = client.startMessage();
message.println(”Testing… 123…”);
client.closeServer();
}
catch (IOException e){
System.out.println(”Things did not go as planned”+e);
}
%>

Looking at the above code it becomes obvious that a scriptlet is probably not the best way to handle this, since it can be error-prone and makes it difficult for a designer to use within an HTML page. This is where using a Customer Tag or JavaBean would be very effective, and using the mail.jar we can easily create one.