Java Reference
In-Depth Information
// Finally, send the message!
Transport
.
send
(
mesg
);
}
catch
catch
(
MessagingException ex
) {
while
while
((
ex
= (
MessagingException
)
ex
.
getNextException
()) !=
null
null
) {
ex
.
printStackTrace
();
}
}
}
/** Simple test case driver */
public
public static
void
main
(
String
[]
av
) {
Sender sm
=
new
static
void
new
Sender
();
sm
.
doSend
();
}
}
Of course, a program that can only send one message to one address is not useful in the long
run. The second version (not shown here, but in the source tree accompanying this topic) al-
lows the To, From, Mailhost, and Subject to come from the command line and reads the mail
text either from a file or from the standard input.
Mail-Enabling a Server Program
Problem
You want to send mail notification from within a program.
Solution
Use the
javax.mail
API directly, or use 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
meth-
od
doSend()
after setting the recipient, sender, subject, and the message text, and
Mailer