Mail-Enabling a Server Program


You want to send mail notification from within a program.


Use the javax.mail API directly, or this Mailer wrapper.


It is not uncommon to want to send email from deep within a non-GUI program such as a server. Here, I package all the standard code into a class called Mailer, which has a series of “set” methods to set the sender, recipient, mail server, etc. You simply call the Mailer method doSend( ) after setting the recipient, sender, subject, and the message text, and Mailer does the rest. Very convenient! So convenient, in fact, that Mailer is part of the com.darwinsys.util package.

For extra generality, the lists of To, CC, and BCC recipients can be set in one of three ways:

  • By passing a string containing one or more recipients, such as “ian, robin”

  • By passing an ArrayList containing all the recipients as strings

  • By adding each recipient as a string

A “full” version will allow the user to type the recipients, the subject, the text, and so on into a GUI, and have some control over the header fields. The MailComposeBean (which we’ll meet in Section 19.10) does all of these, using a Swing-based GUI. MailComposeBean uses this Mailer class to interface with the JavaMail API. Example 19-4 contains the code for the Mailer class.

Example 19-4.

package com.darwinsys.util; import*; import java.util.*; import javax.mail.*; import javax.mail.internet.*; /** Mailer. No relation to Norman. Sends an email message. */ ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.