Java Reference
In-Depth Information
Apart from the endless stream of advertising messages one seems to receive, one of the most common
uses of database-driven e-mail is to help a user who has forgotten his or her password. This is a fairly
simple application, and a JSP page and JavaBean can handle it easily.
To send an e-mail to a member who has lost his or her password, it is necessary to query the
ContactInfo Table to retrieve the member's e-mail address. The query also retrieves the password from
the Login Table. This is the SQL query required to retrieve the member's password and e-mail address
from the Login and ContactInfo Tables:
SELECT l.password, c.email
FROM LOGIN l, CONTACTINFO c
WHERE l.username = 'garfield' AND
l.MemberID = c.MemberID;
For the purposes of this example, all that is required is a simple message containing the member's
password, together with a small amount of explanatory text, as the content. The member's e-mail
address, retrieved from the ContactInfo Table in the database, is plugged in to the Message object's
recipient property.
For simplicity, this example is developed in the context of a JSP application, using the member login
database developed in Chapter 12 . The login JSP page can be set to redirect a user who fails the login
check to a JSP page that uses the SendMailBean developed in the example that follows.
Cross-
Reference
The use of JSP pages and JavaBeans in database-driven Internet
applications is discussed in Chapter 12 .
Using a JSP Page and JavaMail to Send E-mails
The basic SendMailBean is similar to the LoginBean example in Listing 12-9 , with the addition of the
JavaMail component. The example uses a DataSource object to connect to the database and retrieve
the member's password and e-mail address. If the e-mail address is not null, the emailPassword()
method is called to send the password to the user.
The inner workings of the JavaMail-based emailPassword() method are simple. The first step is to
get the System properties object and insert the name of the e-mail host serving the account to be
used to send the e-mail:
props.put("mail.smtp.host", host);
The next step is to get the Session object, which provides the context in which the e-mail is sent:
Session session = Session.getDefaultInstance(props, null);
Once you have a Session object, use it to create a MimeMessage object as shown here:
MimeMessage message = new MimeMessage(session);
All that remains now is to set the properties of the Message object and to send it. In addition to the
Message.Recipient.TO recipient type, the Message object defines these types:
  Message.Recipient.CC
  Message.Recipient.BCC
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(email));
message.setSubject("Password Reminder");
message.setText("Hi "+memberName+",Your password is: "+password);
Search WWH ::




Custom Search