How do I use a ConnectionListener/ConnectionEvent to know when a connection is opened?
Created May 4, 2012
John Zukowski To find out when a connection is opened, attach the ConnectionListener to the Transport you are using to open the connetion. This means you can't use the static Transport.send() method, as you don't have access to the specific Transport you are using. Instead, you need to get the specific transport, and then attach the listener. This is demonstrated in the following example.
import java.util.Properties; import javax.mail.*; import javax.mail.event.*; import javax.mail.internet.*; public class ConnectionExampleListener { public static void main (String args[]) throws Exception { String host = args[0]; String from = args[1]; String to = args[2]; // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", host); // Get session Session session = Session.getInstance(props, null); // Define message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Hello JavaMail"); message.setText("Welcome to JavaMail"); // Define transport Transport transport = session.getTransport("smtp"); ConnectionListener listener = new ConnectionListener() { public void opened(ConnectionEvent e) { System.out.println("Opened"); } public void disconnected(ConnectionEvent e) { System.out.println("Disconnected"); } public void closed(ConnectionEvent e) { System.out.println("Closed"); } }; transport.addConnectionListener(listener); transport.connect(host, "", ""); transport.sendMessage(message, message.getAllRecipients()); transport.close(); Thread.sleep(1000); } }