Example usage for org.apache.commons.net.smtp AuthenticatingSMTPClient isConnected

List of usage examples for org.apache.commons.net.smtp AuthenticatingSMTPClient isConnected

Introduction

In this page you can find the example usage for org.apache.commons.net.smtp AuthenticatingSMTPClient isConnected.

Prototype

public boolean isConnected() 

Source Link

Document

Returns true if the client is currently connected to a server.

Usage

From source file:com.ironiacorp.email.CommonsNetEmailDispatcher.java

@Override
public void sendEmails(Email... emails) {
    AuthenticatingSMTPClient client = null;
    boolean result = false;
    int port = connectionType.port;
    if (serverPort != 0) {
        port = serverPort;/*from   ww  w  .j ava 2  s  .c o m*/
    }

    try {
        client = new AuthenticatingSMTPClient();

        client.connect(serverName, port);
        if (connectionType == EmailServerConnectionType.SSL
                || connectionType == EmailServerConnectionType.TLS) {
            result = client.execTLS();
            if (result == false) {
                throw new IllegalArgumentException("Cannot start secure connection");
            }
        }

        if (authenticationRequired) {
            result = client.auth(AUTH_METHOD.PLAIN, username, password);
            if (result == false) {
                throw new IllegalArgumentException("Incorrect username or password");
            }
        }

        // After connection attempt, you should check the reply code to verify success.
        int reply = client.getReplyCode();
        if (!SMTPReply.isPositiveCompletion(reply)) {
            client.disconnect();
        }

        for (Email email : emails) {
            SimpleSMTPHeader header;
            Iterator<Recipient> i = email.getRecipients().iterator();
            Writer writer = client.sendMessageData();
            String to = null;

            while (i.hasNext()) {
                Recipient recipient = i.next();
                if (to == null && email.getVisibility(recipient) == Visibility.TO) {
                    to = recipient.getEmail();
                } else {
                    client.addRecipient(recipient.getEmail());
                }
            }

            header = new SimpleSMTPHeader(email.getSender().getEmail(), null, email.getSubject());

            writer.write(header.toString());
            result = client.completePendingCommand();
            if (result == false) {
                throw new IllegalArgumentException("Could not send the email");
            }
            client.reset();
        }
    } catch (Exception e) {
        throw new UnsupportedOperationException("Could not send the email", e);
    } finally {
        if (client != null && client.isConnected()) {
            try {
                client.disconnect();
            } catch (IOException e) {
            }
        }

    }
}