Mail-Enabling a Server Program

Problem

You want to send mail notification from within a program.

Solution

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

Discussion

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. Mailer.java

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

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.