Transcript Ch15

Chapter 15
How to use JavaMail to
send email
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 1
Objectives
Applied
 Develop servlets that send email messages to the users of the
application.
Knowledge
 In terms of the SMTP, POP, and MIME protocols, describe how
an email message is sent from one client to another.
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 2
How email works
Sending client
Receiving client
Mail client software
Mail client software
SMTP
POP
Sending server
Mail server software
Murach’s Java Servlets/JSP (2nd Ed.), C15
Receiving server
Mail server software
© 2008, Mike Murach & Associates, Inc.
Slide 3
Three protocols for sending and retrieving email
messages
Protocol
SMTP
POP
IMAP
Description
Simple Mail Transfer Protocol is used to send a message
from one mail server to another.
Post Office Protocol is used to retrieve messages from a
mail server. This protocol transfers all messages from
the mail server to the mail client.
Internet Message Access Protocol is used by web-based
mail services such as Hotmail, Yahoo, and Gmail. This
protocol allows a web browser to read messages that are
stored on the mail server.
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 4
Another protocol that’s used with email
Protocol
MIME
Description
The Multipurpose Internet Message Extension type,
or MIME type, specifies the type of content that can
be sent as a message or attachment.
The JAR files for the JavaMail API
File
mail.jar
activation.jar
Description
Contains the Java classes for the JavaMail API.
Contains the Java classes for the JavaBean Activation
Framework. These classes are necessary for the
JavaMail API to run.
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 5
How to install the JavaMail API
 Locate the download page for the JavaMail API on the Java web
site (www.java.sun.com).
 Click on the Download button and follow the instructions.
 Save the zip file for the JavaMail API to your hard disk. This file
is typically named something like javamail-1_4.zip.
 Extract the files from the zip file.
 Copy the mail.jar file to the JDK’s jre\lib\ext directory.
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 6
How to install the JavaBeans Activation
Framework API
 Locate the download page for the JavaBeans Activation
Framework API on the Java web site (www.java.sun.com).
 Click on the Download button and follow the instructions.
 Save the zip file for the JavaMail API to your hard disk. This file
is typically named something like jaf-1_1.zip.
 Extract the files from the zip file.
 Copy the activation.jar file to the JDK’s jre\lib\ext directory.
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 7
Three packages for sending email
Package
java.util
javax.mail
javax.mail.internet
Murach’s Java Servlets/JSP (2nd Ed.), C15
Description
Contains the Properties class that’s used to set
the properties for the email session.
Contains the Session, Message, Address,
Transport, and MessagingException classes
needed to send a message.
Contains the MimeMessage and
InternetAddress classes needed to send an email
message across the Internet.
© 2008, Mike Murach & Associates, Inc.
Slide 8
Code that uses the JavaMail API to send an email
try
{
// 1 - get a mail session
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
Session session = Session.getDefaultInstance(props);
// 2 - create a message
Message message = new MimeMessage(session);
message.setSubject(subject);
message.setText(body);
// 3 - address the message
Address fromAddress = new InternetAddress(from);
Address toAddress = new InternetAddress(to);
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO,
toAddress);
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 9
Code that uses the JavaMail API (cont.)
// 4 - send the message
Transport.send(message);
}
catch (MessagingException e)
{
log(e.toString());
}
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 10
Common properties that can be set for a Session
object
Property
mail.transport.protocol
mail.smtp.host
mail.smtp.port
mail.smtp.auth
mail.smtp.quitwait
Murach’s Java Servlets/JSP (2nd Ed.), C15
Description
Specifies the protocol that’s used for the
session. For sending email, the protocol is
usually smtp or smtps.
Specifies the host computer for the SMTP
server.
Specifies the port that the SMTP server is
using.
Specifies whether authentication is required
to log in to the SMTP server.
This property can be set to false to prevent an
SSLException from occurring when you
attempt to connect to a GMail SMTP server.
© 2008, Mike Murach & Associates, Inc.
Slide 11
How to get a mail session for a local SMTP server
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
Session session = Session.getDefaultInstance(props);
Another way to get a mail session for a local
SMTP server
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.port", 25);
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 12
How to get a mail session for a remote SMTP
server
Properties props = new Properties();
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", "smtp.gmail.com");
props.put("mail.smtps.port", 465);
props.put("mail.smtps.auth", "true");
props.put("mail.smtps.quitwait", "false");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 13
How to create a mail session
 A Session object contains information about the mail session such
as the procotol, the host, the port, and so on. (This isn’t the same
as the HttpSession object.)
 To set the properties of a Properties object, you can use the put
method to specify a property name and value for each property.
 The static getDefaultInstance method of the Session class returns
the default Session object for the application.
 The setDebug method of the Session object can be used to print
debugging information about the session to a log file.
 If you change the properties for a Session object, you must restart
Tomcat before the changes take effect.
 If the Java application is running on the same computer as the
SMTP server, you can usually use the localhost keyword to
specify the SMTP host.
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 14
How to create a message
Message message = new MimeMessage(session);
How to set the subject line of a message
message.setSubject("Order Confirmation");
How to set the body of a plain text message
message.setText("Thanks for your order!");
How to set the body of an HTML message
message.setContent(
"<H1>Thanks for your order!</H1>", "text/html");
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 15
How to create a message
 You can use the MimeMessage class that’s stored in the
javax.mail.internet package to create a message. This message
extends the Message class that’s stored in the java.mail package.
 To create a MimeMessage object, you supply a valid Session
object to the MimeMessage constructor.
 Once you’ve created a MimeMessage object, you can use the
setSubject and setText methods to set the subject line and body of
the email message. This automatically sets the MIME type to
text/plain.
 You can use the setContent method to include an HTML
document as the body of the message. To do that, the first
argument specifies a string for the HTML document, and the
second argument specifies text/html as the MIME type.
 All of these methods throw a javax.mail.MessagingException.
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 16
How to set the From address
Address fromAddress = new
InternetAddress("[email protected]");
message.setFrom(fromAddress);
How to set the To address
Address toAddress =
new InternetAddress("[email protected]");
message.setRecipient(
Message.RecipientType.TO, toAddress);
How to set the CC address
Address ccAddress = new InternetAddress("[email protected]");
message.setRecipient(
Message.RecipientType.CC, ccAddress);
How to set the BCC address
Address bccAddress =
new InternetAddress("[email protected]");
message.setRecipient(
Message.RecipientType.BCC, bccAddress);
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 17
How to include an email address and a name
Address toAddress = new InternetAddress(
"[email protected]", "Andrea Steelman");
How to send a message to multiple recipients
Address[] mailList = {
new InternetAddress("[email protected]"),
new InternetAddress("[email protected]"),
new InternetAddress("[email protected]") };
message.setRecipients(
Message.RecipientType.TO, mailList);
How to add recipients to a message
Address toAddress =
new InternetAddress("[email protected]");
message.addRecipient(
Message.RecipientType.TO, toAddress);
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 18
How to address a message
 Use the InternetAddress class that’s stored in the
javax.mail.internet package.
 To set the From address, use the setFrom method of the
MimeMessage object. To set the To, CC (carbon copy), and BCC
(blind carbon copy) addresses, use the setRecipient and
setRecipients methods of the MimeMessage object.
 To include a name for an email address, you can add a second
argument to the InternetAddress constructor. However, this
constructor throws an exception of the
java.io.UnsupportedEncodingException type.
 To send an email message to multiple recipients, you can pass an
array of Address objects to the setRecipients method. To add
email addresses to any existing addresses for a message, use the
addRecipient and addRecipients methods.
 All of these methods throw a javax.mail.MessagingException.
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 19
How to send a message when no authentication is
required
Transport.send(message);
How to send a message when authentication is
required
Transport transport = session.getTransport();
transport.connect("[email protected]", "sesame");
transport.sendMessage(
message, message.getAllRecipients());
transport.close();
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 20
How to send a message
 If the SMTP server doesn’t require authentication, you can use the
static send method of the Transport class.
 If the SMTP server requires authentication, you can use the static
getTransport method of the Transport class to return a Transport
object. Then, you can use the connect method to specify a
username and password that can be used to connect to the server;
the sendMessage method to send the message; and the close
method to close the connection.
 If the SMTP host is incorrect in the session object or if a message
can’t be sent, the send method will throw a SendFailedException
object. You can use this object to return invalid addresses, valid
addresses that have been sent, and valid addresses that haven’t
been sent.
 The SendFailedException class inherits the MessagingException
class.
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 21
A helper class for sending an email with a local
SMTP server
package util;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class MailUtilLocal
{
public static void sendMail(String to, String from,
String subject, String body, boolean bodyIsHTML)
throws MessagingException
{
// 1 - get a mail session
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.port", 25);
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 22
A helper class for sending an email with a local
SMTP server (cont.)
// 2 - create a message
Message message = new MimeMessage(session);
message.setSubject(subject);
if (bodyIsHTML)
message.setContent(body, "text/html");
else
message.setText(body);
// 3 - address the message
Address fromAddress = new InternetAddress(from);
Address toAddress = new InternetAddress(to);
message.setFrom(fromAddress);
message.setRecipient(
Message.RecipientType.TO, toAddress);
// 4 - send the message
Transport.send(message);
}
}
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 23
A servlet that sends an email
package email;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.MessagingException;
import business.User;
import data.UserIO;
import util.*;
public class AddToEmailListServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException
{
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 24
A servlet that sends an email (cont.)
// get parameters from the request
String firstName =
request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress =
request.getParameter("emailAddress");
// create the User object and write it to a file
User user = new User(
firstName, lastName, emailAddress);
ServletContext sc = getServletContext();
String path = sc.getRealPath(
"/WEB-INF/EmailList.txt");
UserIO.addRecord(user, path);
// store the User object in the session
HttpSession session = request.getSession();
session.setAttribute("user", user);
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 25
A servlet that sends an email (cont.)
// send email to user
String to = emailAddress;
String from = "[email protected]";
String subject = "Welcome to our email list";
String body = "Dear " + firstName + ",\n\n" +
"Thanks for joining our email list. " +
"We'll make sure to send you announcements " +
"about new products and promotions.\n" +
"Have a great day and thanks again!\n\n" +
"Kelly Slivkoff\n" +
"Mike Murach & Associates";
boolean isBodyHTML = false;
try
{
MailUtilLocal.sendMail(
to, from, subject, body, isBodyHTML);
}
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 26
A servlet that sends an email (cont.)
catch (MessagingException e)
{
String errorMessage =
"ERROR: Unable to send email. " +
"Check Tomcat logs for details.<br>" +
"NOTE: You may need to configure your " +
"system as described in chapter 15.<br>" +
"ERROR MESSAGE: " + e.getMessage();
request.setAttribute(
"errorMessage", errorMessage);
this.log(
"Unable to send email. \n" +
"Here is the email you tried to send: \n" +
"=====================================\n" +
"TO: " + emailAddress + "\n" +
"FROM: " + from + "\n" +
"SUBJECT: " + subject + "\n" +
"\n" +
body + "\n\n");
}
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 27
A servlet that sends an email (cont.)
// forward request and response to JSP page
String url = "/display_email_entry.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 28
A helper class for sending an email with a remote
SMTP server
package util;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class MailUtilYahoo
{
public static void sendMail(String to, String from,
String subject, String body, boolean bodyIsHTML)
throws MessagingException
{
// 1 - get a mail session
Properties props = new Properties();
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", "smtp.mail.yahoo.com");
props.put("mail.smtps.port", 465);
props.put("mail.smtps.auth", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 29
A helper class for sending an email with a remote
SMTP server (cont.)
// 2 - create a message
Message message = new MimeMessage(session);
message.setSubject(subject);
if (bodyIsHTML)
message.setContent(body, "text/html");
else
message.setText(body);
// 3 - address the message
Address fromAddress = new InternetAddress(from);
Address toAddress = new InternetAddress(to);
message.setFrom(fromAddress);
message.setRecipient(
Message.RecipientType.TO, toAddress);
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 30
A helper class for sending an email with a remote
SMTP server (cont.)
// 4 - send the message
Transport transport = session.getTransport();
transport.connect("johnsmith", "sesame");
transport.sendMessage(
message, message.getAllRecipients());
transport.close();
}
}
Murach’s Java Servlets/JSP (2nd Ed.), C15
© 2008, Mike Murach & Associates, Inc.
Slide 31