Java Reference
In-Depth Information
msg . setText ( "Resistance is futile. You will be assimilated!" );
Next we specify the transport we want. In 2013, smtps (SMTP over TLS) is the customary
choice:
Transport t = session . getTransport ( "smtps" );
Once you have a transport, you connect it to a specified host with a given username and
password:
t . connect ( "smtp.gmail.com" , "elharo" , "mypassword" );
SMTP connections used to be unauthenticated with no username or
password. However, spammer abuse made this sort of open relay in‐
feasible in the 21st century. Going forward, even usernames and pass‐
words are less than perfectly secure. I would not be surprised if this
example stops working during the lifetime of this topic and some more
secure oAuth2 or two factor system becomes required to send email.
Next the send() method connects to the mail server and sends the message on its way:
t . sendMessage ( msg , msg . getAllRecipients ());
The second argument to sendMessage() is an array of addresses to send the message
to. Instead of using the addresses in the message itself, you could add additional email
addresses. For example:
Address [] addresses = {
new InternetAddress ( "wilma@example.org" ),
new InternetAddress ( "fred@example.org" ),
new InternetAddress ( "daphne@example.org" ),
new InternetAddress ( "shaggy@example.org" )
};
transport . sendMessage ( msg , addresses );
Finally the close() method shuts down the connection. Transport does not implement
AutoCloseable , so even in Java 7 programs normally use the dispose pattern and close
the transport in a finally block:
Transport t ;
try {
// work with the transport...
} catch ( MessagingException ex ) {
ex . printStackTrace ();
} finally {
if ( t != null ) {
try {
t . close ();
} catch ( MessagingException ex ) {
Search WWH ::




Custom Search