Java Reference
In-Depth Information
return internetAddress.getAddress();
}
How It Works
After connecting to the IMAP server, the example requests all messages received. The
code skips over the ones that are marked as
SEEN
. To do so, the recipe uses the
Ar-
rays.AsList
to convert the array of system message flags into an
ArrayList
.
Once the list is created, it is a matter of querying the list to see whether it contains the
Flag.SEEN enum
value. If that value is present, the example skips to the next item.
When an unread message is found, the message is processed by the
pro-
cessMessage()
method. The method subscribes or unsubscribes the sender of the
message depending on the start of the subject line. (This is akin to a mailing list, where
sending a message with the subject of “subscribe” adds the sender to the mailing list.)
After determining which command to execute, the code proceeds to extract the
sender's e-mail from the message. To do so, the
processMessage()
calls the
ex-
tractEmail()
method. Each message contains an array of possible “From” ad-
dresses. These
Address
objects are generic because the
Address
object can repres-
ent Internet or newsgroup addresses. After checking that the
Address
object is indeed
an
InternetAddress
, the code casts the
Address
object as an
InternetAd-
dress
and calls the
getAddress()
method, which contains the actual e-mail ad-
dress.
Once the e-mail address is extracted, the recipe calls
subscribe
or
unsub-
scribe
, depending on the subject line. If the message could be understood (meaning
that the message was processed), the
processMessage()
method returns
true
(if
it couldn't understand the message, it returns
false
). In the
checkForMail()
method, when the
processMessage()
method returns
true
, the message is
flagged for deletion (by calling
message.setFlag(Flags.Flag.DELETED,
true)
; otherwise, the message is just flagged as
Seen
. This allows the message to
still be around if it wasn't understood or deleted if it was processed. Finally, to commit
the new flags on the messages (and expunge deleted messages), you need to call the
inbox.close(true)
method.
Summary