Java Reference
In-Depth Information
t
.
connect
(
hostname
,
username
,
password
);
t
.
sendMessage
(
msg
,
msg
.
getAllRecipients
());
}
catch
(
MessagingException
ex
)
{
ex
.
printStackTrace
();
}
finally
{
// Transport does not implement Autocloseable :-(
if
(
t
!=
null
)
try
{
t
.
close
();
}
catch
(
MessagingException
e
)
{
// ignore
}
}
}
};
Thread
t
=
new
Thread
(
r
);
t
.
start
();
message
.
setText
(
""
);
}
catch
(
MessagingException
ex
)
{
JOptionPane
.
showMessageDialog
(
getRootPane
(),
"Error sending message: "
+
ex
.
getMessage
());
}
}
}
public
static
void
main
(
String
[]
args
)
{
SwingUtilities
.
invokeLater
(
new
Runnable
()
{
@Override
public
void
run
()
{
SMTPClient
client
=
new
SMTPClient
();
// I set up the exit behavior here rather than in
// the constructor since other programs that use this class
// may not want to exit the application when the SMTPClient
// window closes.
client
.
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
client
.
setVisible
(
true
);
}
});
}
}
This is far from an ideal program. The GUI could be more cleanly separated from the
mailing code. And it would be better to bring up an error dialog if something went
wrong rather than just printing a stack trace of the exception on
System.err
. However,
since none of that would teach us anything about the JavaMail API, I leave it all as an
exercise for the interested reader.