JSP Tutorial


Sending e-mail from JSP

To be able to send e-mail, you need access to an "SMTP server". SMTP stands for "Simple Mail Transfer Protocol". Most of the email on the internet is sent using SMTP servers.

If your email address is "you@yourhost.com", then there is a good chance your SMTP server is either "yourhost.com" or something like "mail.yourhost.com" or "smtp.yourhost.com". You need to find out exactly what it is. Your email program should have a "Settings" page which shows you the name of your SMTP server (perhaps shown as "mail server" or "outgoing mail server".)

(If you have web-based email, you probably won't be able to send email out directly.)

Once you have the SMTP server information, you are ready to send email out from your JSP pages. Following is a small sample that uses the Blazix Tag library to send an email with an attachment.

First of all, let us write an HTML page to start things off.

<HTML>
<BODY>
<FORM METHOD=POST ACTION="SendMail.jsp">
Please enter name: <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
Please enter email address: <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>

Now let us write the target JSP, SendMail.jsp.  Replace "yoursmtphost.com" by your SMTP server, and "you@youremail.com" by your email address.  Before testing it, also create a file "C:\contents.txt" which will be sent as an attachment.

<%@ taglib prefix="blx" uri="/blx.tld" %>
<HTML>
<BODY>
<%
  // Get username.
  String email = request.getParameter( "email" );
%>
<% if ( email == null || email.equals( "" )) { %>
Please enter an email address.
<% } else { %>
<blx:email host="yoursmtphost.com" from="you@youremail.com"> 
<blx:emailTo><%= email %></blx:emailTo> 
Thank you for registering with us.  You registered the
following name: <%= request.getParameter( "username" ) %>

Your registration was received at <%= new java.util.Date() %>

Attached, please find a contents file.
<blx:emailAttach file="C:\\contents.txt" 
      contentType="text/plain" name="contents.txt/> 
</blx:email> 
<!--  Also write out some HTML -->
Thank you.  A confirmation email has been sent to <%= email %>
<% } %>
</BODY>
</HTML>

Exercise:  1)  Send an HTML file as an attachment, changing the contentType to "text/html" instead of "text/plain".
2) Send the HTML file as an attachment, without using any other text.  In the "blx:email" tag, also set "noText=true".
 
Contents