Java Reference
In-Depth Information
try
{
System
.
out
.
println
(
message
.
getSubject
());
}
catch
(
MessagingException
e
)
{
System
.
out
.
println
(
"New message arrived!"
);
}
}
}
@Override
public
void
messagesRemoved
(
MessageCountEvent
event
)
{
// ignore
}
}
This class notifies the user by printing a message on the console. Of course, you could
pop up an alert in a GUI, ring a bell, or use any other technique you like.
Next you install this listener on the folder you wish to monitor as shown in
Example 9-2
.
Example 9-2. Mailbox Monitor
import
java.util.*
;
import
javax.mail.*
;
import
javax.mail.event.*
;
import
com.sun.mail.imap.IMAPStore
;
public
class
GMailMonitor
{
public
static
void
main
(
String
[]
args
)
throws
InterruptedException
{
String
username
=
args
[
0
];
String
password
=
args
[
1
];
try
{
Session
session
=
Session
.
getInstance
(
new
Properties
());
final
IMAPStore
store
=
(
IMAPStore
)
session
.
getStore
(
"imaps"
);
store
.
connect
(
"imap.gmail.com"
,
username
+
"@gmail.com"
,
password
);
final
Folder
inbox
=
store
.
getFolder
(
"INBOX"
);
if
(
inbox
==
null
)
{
System
.
out
.
println
(
"No INBOX"
);
System
.
exit
(
1
);
}
inbox
.
open
(
Folder
.
READ_ONLY
);
MessageCountListener
countListener
=
new
MessageArrival
();
inbox
.
addMessageCountListener
(
countListener
);
Runnable
r
=
new
Runnable
()
{
@Override
public
void
run
()
{
while
(
true
)
{
try
{
System
.
out
.
println
(
inbox
.
getMessageCount
());