Example usage for org.apache.commons.net.smtp SMTPClient disconnect

List of usage examples for org.apache.commons.net.smtp SMTPClient disconnect

Introduction

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

Prototype

@Override
public void disconnect() throws IOException 

Source Link

Document

Closes the connection to the SMTP server and sets to null some internal data so that the memory may be reclaimed by the garbage collector.

Usage

From source file:com.clustercontrol.port.protocol.ReachAddressSMTP.java

/**
 * SMTP????????/*from w w  w. j a v a 2  s  .  co m*/
 * 
 * @param addressText
 * @return SMTP
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the SMTP Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        SMTPClient client = new SMTPClient();

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                client.setDefaultTimeout(m_timeout);

                start = HinemosTime.currentTimeMillis();
                client.connect(address, m_portNo);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;

                result = client.getReplyString();

                int reply = client.getReplyCode();

                if (SMTPReply.isPositiveCompletion(reply)) {
                    if (m_response > 0) {
                        if (m_response < m_timeout) {
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        } else {
                            m_response = m_timeout;
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        }
                    } else {
                        result = result + ("\n" + "Response Time < 1ms");
                    }

                    retry = false;
                    isReachable = true;
                } else {
                    retry = false;
                    isReachable = false;
                }

            } catch (SocketException e) {
                result = (e.getMessage() + "[SocketException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (client.isConnected()) {
                    try {
                        client.disconnect();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(SMTP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.warn("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage(), e);
        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:com.google.gerrit.server.mail.SmtpEmailSender.java

@Override
public void send(final Address from, Collection<Address> rcpt, final Map<String, EmailHeader> callerHeaders,
        final String body) throws EmailException {
    if (!isEnabled()) {
        throw new EmailException("Sending email is disabled");
    }/*from  w  ww . j  ava2s  . c  om*/

    final Map<String, EmailHeader> hdrs = new LinkedHashMap<String, EmailHeader>(callerHeaders);
    setMissingHeader(hdrs, "MIME-Version", "1.0");
    setMissingHeader(hdrs, "Content-Type", "text/plain; charset=UTF-8");
    setMissingHeader(hdrs, "Content-Transfer-Encoding", "8bit");
    setMissingHeader(hdrs, "Content-Disposition", "inline");
    setMissingHeader(hdrs, "User-Agent", "Gerrit/" + Version.getVersion());
    if (importance != null) {
        setMissingHeader(hdrs, "Importance", importance);
    }
    if (expiryDays > 0) {
        Date expiry = new Date(System.currentTimeMillis() + expiryDays * 24 * 60 * 60 * 1000);
        setMissingHeader(hdrs, "Expiry-Date",
                new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z").format(expiry));
    }

    StringBuffer rejected = new StringBuffer();
    try {
        final SMTPClient client = open();
        try {
            if (!client.setSender(from.email)) {
                throw new EmailException("Server " + smtpHost + " rejected from address " + from.email);
            }

            /* Do not prevent the email from being sent to "good" users simply
             * because some users get rejected.  If not, a single rejected
             * project watcher could prevent email for most actions on a project
             * from being sent to any user!  Instead, queue up the errors, and
             * throw an exception after sending the email to get the rejected
             * error(s) logged.
             */
            for (Address addr : rcpt) {
                if (!client.addRecipient(addr.email)) {
                    String error = client.getReplyString();
                    rejected.append("Server " + smtpHost + " rejected recipient " + addr + ": " + error);
                }
            }

            Writer w = client.sendMessageData();
            if (w == null) {
                /* Include rejected recipient error messages here to not lose that
                 * information. That piece of the puzzle is vital if zero recipients
                 * are accepted and the server consequently rejects the DATA command.
                 */
                throw new EmailException(
                        rejected + "Server " + smtpHost + " rejected DATA command: " + client.getReplyString());
            }
            w = new BufferedWriter(w);

            for (Map.Entry<String, EmailHeader> h : hdrs.entrySet()) {
                if (!h.getValue().isEmpty()) {
                    w.write(h.getKey());
                    w.write(": ");
                    h.getValue().write(w);
                    w.write("\r\n");
                }
            }

            w.write("\r\n");
            w.write(body);
            w.flush();
            w.close();

            if (!client.completePendingCommand()) {
                throw new EmailException(
                        "Server " + smtpHost + " rejected message body: " + client.getReplyString());
            }

            client.logout();
            if (rejected.length() > 0) {
                throw new EmailException(rejected.toString());
            }
        } finally {
            client.disconnect();
        }
    } catch (IOException e) {
        throw new EmailException("Cannot send outgoing email", e);
    }
}

From source file:com.google.gerrit.server.mail.send.SmtpEmailSender.java

@Override
public void send(final Address from, Collection<Address> rcpt, final Map<String, EmailHeader> callerHeaders,
        String textBody, @Nullable String htmlBody) throws EmailException {
    if (!isEnabled()) {
        throw new EmailException("Sending email is disabled");
    }// w ww  .j  a  v a2  s.  co  m

    final Map<String, EmailHeader> hdrs = new LinkedHashMap<>(callerHeaders);
    setMissingHeader(hdrs, "MIME-Version", "1.0");
    setMissingHeader(hdrs, "Content-Transfer-Encoding", "8bit");
    setMissingHeader(hdrs, "Content-Disposition", "inline");
    setMissingHeader(hdrs, "User-Agent", "Gerrit/" + Version.getVersion());
    if (importance != null) {
        setMissingHeader(hdrs, "Importance", importance);
    }
    if (expiryDays > 0) {
        Date expiry = new Date(TimeUtil.nowMs() + expiryDays * 24 * 60 * 60 * 1000L);
        setMissingHeader(hdrs, "Expiry-Date",
                new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z").format(expiry));
    }

    String encodedBody;
    if (htmlBody == null) {
        setMissingHeader(hdrs, "Content-Type", "text/plain; charset=UTF-8");
        encodedBody = textBody;
    } else {
        String boundary = generateMultipartBoundary(textBody, htmlBody);
        setMissingHeader(hdrs, "Content-Type",
                "multipart/alternative; boundary=\"" + boundary + "\"; charset=UTF-8");
        encodedBody = buildMultipartBody(boundary, textBody, htmlBody);
    }

    StringBuffer rejected = new StringBuffer();
    try {
        final SMTPClient client = open();
        try {
            if (!client.setSender(from.getEmail())) {
                throw new EmailException("Server " + smtpHost + " rejected from address " + from.getEmail());
            }

            /* Do not prevent the email from being sent to "good" users simply
             * because some users get rejected.  If not, a single rejected
             * project watcher could prevent email for most actions on a project
             * from being sent to any user!  Instead, queue up the errors, and
             * throw an exception after sending the email to get the rejected
             * error(s) logged.
             */
            for (Address addr : rcpt) {
                if (!client.addRecipient(addr.getEmail())) {
                    String error = client.getReplyString();
                    rejected.append("Server ").append(smtpHost).append(" rejected recipient ").append(addr)
                            .append(": ").append(error);
                }
            }

            Writer messageDataWriter = client.sendMessageData();
            if (messageDataWriter == null) {
                /* Include rejected recipient error messages here to not lose that
                 * information. That piece of the puzzle is vital if zero recipients
                 * are accepted and the server consequently rejects the DATA command.
                 */
                throw new EmailException(
                        rejected + "Server " + smtpHost + " rejected DATA command: " + client.getReplyString());
            }
            try (Writer w = new BufferedWriter(messageDataWriter)) {
                for (Map.Entry<String, EmailHeader> h : hdrs.entrySet()) {
                    if (!h.getValue().isEmpty()) {
                        w.write(h.getKey());
                        w.write(": ");
                        h.getValue().write(w);
                        w.write("\r\n");
                    }
                }

                w.write("\r\n");
                w.write(encodedBody);
                w.flush();
            }

            if (!client.completePendingCommand()) {
                throw new EmailException(
                        "Server " + smtpHost + " rejected message body: " + client.getReplyString());
            }

            client.logout();
            if (rejected.length() > 0) {
                throw new EmailException(rejected.toString());
            }
        } finally {
            client.disconnect();
        }
    } catch (IOException e) {
        throw new EmailException("Cannot send outgoing email", e);
    }
}

From source file:com.xpn.xwiki.XWiki.java

/**
 * @deprecated replaced by the <a href="http://code.xwiki.org/xwiki/bin/view/Plugins/MailSenderPlugin">Mail Sender
 *             Plugin</a>//  w  w  w. ja v a 2s.  c o  m
 */
@Deprecated
private void sendMessageOld(String sender, String[] recipient, String message, XWikiContext context)
        throws XWikiException {
    SMTPClient smtpc = null;
    try {
        String server = getXWikiPreference("smtp_server", context);
        String port = getXWikiPreference("smtp_port", context);
        String login = getXWikiPreference("smtp_login", context);

        if (context.get("debugMail") != null) {
            StringBuffer msg = new StringBuffer(message);
            msg.append("\n Recipient: ");
            msg.append(recipient);
            recipient = ((String) context.get("debugMail")).split(",");
            message = msg.toString();
        }

        if ((server == null) || server.equals("")) {
            server = "127.0.0.1";
        }
        if ((port == null) || (port.equals(""))) {
            port = "25";
        }
        if ((login == null) || login.equals("")) {
            login = InetAddress.getLocalHost().getHostName();
        }

        smtpc = new SMTPClient();
        smtpc.connect(server, Integer.parseInt(port));
        int reply = smtpc.getReplyCode();
        if (!SMTPReply.isPositiveCompletion(reply)) {
            Object[] args = { server, port, Integer.valueOf(reply), smtpc.getReplyString() };
            throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL,
                    XWikiException.ERROR_XWIKI_EMAIL_CONNECT_FAILED,
                    "Could not connect to server {0} port {1} error code {2} ({3})", null, args);
        }

        if (smtpc.login(login) == false) {
            reply = smtpc.getReplyCode();
            Object[] args = { server, port, Integer.valueOf(reply), smtpc.getReplyString() };
            throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL,
                    XWikiException.ERROR_XWIKI_EMAIL_LOGIN_FAILED,
                    "Could not login to mail server {0} port {1} error code {2} ({3})", null, args);
        }

        if (smtpc.sendSimpleMessage(sender, recipient, message) == false) {
            reply = smtpc.getReplyCode();
            Object[] args = { server, port, Integer.valueOf(reply), smtpc.getReplyString() };
            throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL,
                    XWikiException.ERROR_XWIKI_EMAIL_SEND_FAILED,
                    "Could not send mail to server {0} port {1} error code {2} ({3})", null, args);
        }

    } catch (IOException e) {
        Object[] args = { sender, recipient };
        throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL,
                XWikiException.ERROR_XWIKI_EMAIL_ERROR_SENDING_EMAIL,
                "Exception while sending email from {0} to {1}", e, args);
    } finally {
        if ((smtpc != null) && (smtpc.isConnected())) {
            try {
                smtpc.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.apache.axis.transport.mail.MailSender.java

/**
 * Send the soap request message to the server
 *
 * @param msgContext message context/*from   w ww.  j  a  va  2s .  c  om*/
 *
 * @return id for the current message
 * @throws Exception
 */
private String writeUsingSMTP(MessageContext msgContext) throws Exception {
    String id = (new java.rmi.server.UID()).toString();
    String smtpHost = msgContext.getStrProp(MailConstants.SMTP_HOST);

    SMTPClient client = new SMTPClient();
    client.connect(smtpHost);

    // After connection attempt, you should check the reply code to verify
    // success.
    System.out.print(client.getReplyString());
    int reply = client.getReplyCode();
    if (!SMTPReply.isPositiveCompletion(reply)) {
        client.disconnect();
        AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
        throw fault;
    }

    client.login(smtpHost);
    System.out.print(client.getReplyString());
    reply = client.getReplyCode();
    if (!SMTPReply.isPositiveCompletion(reply)) {
        client.disconnect();
        AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
        throw fault;
    }

    String fromAddress = msgContext.getStrProp(MailConstants.FROM_ADDRESS);
    String toAddress = msgContext.getStrProp(MailConstants.TO_ADDRESS);

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(fromAddress));
    msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAddress));

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message reqMessage = msgContext.getRequestMessage();

    msg.addHeader(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent"));
    msg.addHeader(HTTPConstants.HEADER_SOAP_ACTION, action);
    msg.setDisposition(MimePart.INLINE);
    msg.setSubject(id);

    ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024);
    reqMessage.writeTo(out);
    msg.setContent(out.toString(), reqMessage.getContentType(msgContext.getSOAPConstants()));

    ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024);
    msg.writeTo(out2);

    client.setSender(fromAddress);
    System.out.print(client.getReplyString());
    client.addRecipient(toAddress);
    System.out.print(client.getReplyString());

    Writer writer = client.sendMessageData();
    System.out.print(client.getReplyString());
    writer.write(out2.toString());
    writer.flush();
    writer.close();

    System.out.print(client.getReplyString());
    if (!client.completePendingCommand()) {
        System.out.print(client.getReplyString());
        AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null);
        throw fault;
    }
    System.out.print(client.getReplyString());
    client.logout();
    client.disconnect();
    return id;
}

From source file:org.apache.axis.transport.mail.MailWorker.java

/**
 * Send the soap request message to the server
 * /*from  w ww . ja  va 2 s .c  o m*/
 * @param msgContext
 * @param smtpHost
 * @param sendFrom
 * @param replyTo
 * @param output
 * @throws Exception
 */
private void writeUsingSMTP(MessageContext msgContext, String smtpHost, String sendFrom, String replyTo,
        String subject, Message output) throws Exception {
    SMTPClient client = new SMTPClient();
    client.connect(smtpHost);

    // After connection attempt, you should check the reply code to verify
    // success.
    System.out.print(client.getReplyString());
    int reply = client.getReplyCode();
    if (!SMTPReply.isPositiveCompletion(reply)) {
        client.disconnect();
        AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
        throw fault;
    }

    client.login(smtpHost);
    System.out.print(client.getReplyString());
    reply = client.getReplyCode();
    if (!SMTPReply.isPositiveCompletion(reply)) {
        client.disconnect();
        AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
        throw fault;
    }

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(sendFrom));
    msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(replyTo));
    msg.setDisposition(MimePart.INLINE);
    msg.setSubject(subject);

    ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024);
    output.writeTo(out);
    msg.setContent(out.toString(), output.getContentType(msgContext.getSOAPConstants()));

    ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024);
    msg.writeTo(out2);

    client.setSender(sendFrom);
    System.out.print(client.getReplyString());
    client.addRecipient(replyTo);
    System.out.print(client.getReplyString());

    Writer writer = client.sendMessageData();
    System.out.print(client.getReplyString());
    writer.write(out2.toString());
    writer.flush();
    writer.close();

    System.out.print(client.getReplyString());
    if (!client.completePendingCommand()) {
        System.out.print(client.getReplyString());
        AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null);
        throw fault;
    }
    System.out.print(client.getReplyString());
    client.logout();
    client.disconnect();
}

From source file:org.apache.camel.component.james.smtp.SMTPTest.java

/**
 * Test send matching message.//from   w w  w .  jav a  2  s . c om
 * 
 * @throws Exception
 *             the exception
 */
@SuppressWarnings("unchecked")
@Test
public void testSendMatchingMessage() throws Exception {
    String sender = "sender@localhost";
    String rcpt = "rcpt@localhost";
    String body = "Subject: test\r\n\r\nTestmail";
    SMTPClient client = new SMTPClient();
    client.connect("localhost", port);
    client.helo("localhost");
    client.setSender(sender);
    client.addRecipient(rcpt);

    client.sendShortMessageData(body);
    client.quit();
    client.disconnect();
    resultEndpoint.expectedMessageCount(1);
    resultEndpoint.expectedBodyReceived().body(InputStream.class);
    Exchange ex = resultEndpoint.getReceivedExchanges().get(0);
    Map<String, Object> headers = ex.getIn().getHeaders();
    assertEquals(sender, headers.get(MailEnvelopeMessage.SMTP_SENDER_ADRRESS));
    assertEquals(rcpt, headers.get(MailEnvelopeMessage.SMTP_RCPT_ADRRESS_LIST));

    // check type converter
    MimeMessage message = ex.getIn().getBody(MimeMessage.class);
    Enumeration<Header> mHeaders = message.getAllHeaders();
    Header header = null;
    while (mHeaders.hasMoreElements()) {
        header = mHeaders.nextElement();
        if (header.getName().equals("Subject")) {
            break;
        }
    }
    assertNotNull(header);
    assertEquals("Subject", header.getName());
    assertEquals(header.getValue(), "test");

    resultEndpoint.assertIsSatisfied();
}

From source file:org.apache.common.net.examples.mail.SMTPMail.java

public final static void main(String[] args) {
    String sender, recipient, subject, filename, server, cc;
    List<String> ccList = new ArrayList<String>();
    BufferedReader stdin;/*from w ww . java 2  s  .c o  m*/
    FileReader fileReader = null;
    Writer writer;
    SimpleSMTPHeader header;
    SMTPClient client;

    if (args.length < 1) {
        System.err.println("Usage: mail smtpserver");
        System.exit(1);
    }

    server = args[0];

    stdin = new BufferedReader(new InputStreamReader(System.in));

    try {
        System.out.print("From: ");
        System.out.flush();

        sender = stdin.readLine();

        System.out.print("To: ");
        System.out.flush();

        recipient = stdin.readLine();

        System.out.print("Subject: ");
        System.out.flush();

        subject = stdin.readLine();

        header = new SimpleSMTPHeader(sender, recipient, subject);

        while (true) {
            System.out.print("CC <enter one address per line, hit enter to end>: ");
            System.out.flush();

            cc = stdin.readLine();

            if (cc == null || cc.length() == 0) {
                break;
            }

            header.addCC(cc.trim());
            ccList.add(cc.trim());
        }

        System.out.print("Filename: ");
        System.out.flush();

        filename = stdin.readLine();

        try {
            fileReader = new FileReader(filename);
        } catch (FileNotFoundException e) {
            System.err.println("File not found. " + e.getMessage());
        }

        client = new SMTPClient();
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

        client.connect(server);

        if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
            client.disconnect();
            System.err.println("SMTP server refused connection.");
            System.exit(1);
        }

        client.login();

        client.setSender(sender);
        client.addRecipient(recipient);

        for (String recpt : ccList) {
            client.addRecipient(recpt);
        }

        writer = client.sendMessageData();

        if (writer != null) {
            writer.write(header.toString());
            Util.copyReader(fileReader, writer);
            writer.close();
            client.completePendingCommand();
        }

        if (fileReader != null) {
            fileReader.close();
        }

        client.logout();

        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:org.apache.commons.net.examples.mail.SMTPMail.java

public static void main(String[] args) {
    String sender, recipient, subject, fileName, server, cc;
    List<String> ccList = new ArrayList<String>();
    BufferedReader stdin;//from   w w w . j  a v a 2s .  c  om
    FileReader fileReader = null;
    Writer writer;
    SimpleSMTPHeader header;
    SMTPClient client;

    if (args.length < 1) {
        System.err.println("Usage: SMTPMail <smtpserver>");
        System.exit(1);
    }

    server = args[0];

    stdin = new BufferedReader(new InputStreamReader(System.in));

    try {
        System.out.print("From: ");
        System.out.flush();

        sender = stdin.readLine();

        System.out.print("To: ");
        System.out.flush();

        recipient = stdin.readLine();

        System.out.print("Subject: ");
        System.out.flush();

        subject = stdin.readLine();

        header = new SimpleSMTPHeader(sender, recipient, subject);

        while (true) {
            System.out.print("CC <enter one address per line, hit enter to end>: ");
            System.out.flush();

            cc = stdin.readLine();

            if (cc == null || cc.length() == 0) {
                break;
            }

            header.addCC(cc.trim());
            ccList.add(cc.trim());
        }

        System.out.print("Filename: ");
        System.out.flush();

        fileName = stdin.readLine();

        try {
            fileReader = new FileReader(fileName);
        } catch (FileNotFoundException e) {
            System.err.println("File not found. " + e.getMessage());
        }

        client = new SMTPClient();
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

        client.connect(server);

        if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
            client.disconnect();
            System.err.println("SMTP server refused connection.");
            System.exit(1);
        }

        client.login();

        client.setSender(sender);
        client.addRecipient(recipient);

        for (String recpt : ccList) {
            client.addRecipient(recpt);
        }

        writer = client.sendMessageData();

        if (writer != null) {
            writer.write(header.toString());
            Util.copyReader(fileReader, writer);
            writer.close();
            client.completePendingCommand();
        }

        if (fileReader != null) {
            fileReader.close();
        }

        client.logout();

        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:org.apache.james.protocols.lmtp.AbstractLMTPServerTest.java

@Override
public void testMailWithoutBrackets() throws Exception {
    TestMessageHook hook = new TestMessageHook();
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;/*w w  w  .  j  a  v  a  2  s.c om*/
    try {
        server = createServer(createProtocol(hook), address);
        server.bind();

        SMTPClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue(SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.helo("localhost");
        assertTrue(SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.mail(SENDER);
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.quit();
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));
        client.disconnect();

        Iterator<MailEnvelope> queued = hook.getQueued().iterator();
        assertFalse(queued.hasNext());

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}