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

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

Introduction

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

Prototype

public void connect(InetAddress host, int port) throws SocketException, IOException 

Source Link

Document

Opens a Socket connected to a remote host at the specified port and originating from the current host at a system assigned port.

Usage

From source file:me.normanmaurer.camel.smtp.SMTPTest.java

@SuppressWarnings("unchecked")
@Test//from ww  w  .  ja v a 2s  . co m
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", 2525);
    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:com.google.code.camel.smtp.SMTPTest.java

@SuppressWarnings("unchecked")
@Test//  w ww . j a v a  2 s . co  m
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", 2525);
    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();
    System.out.println(header.toString());
    if (header.getName().equals("Subject")) {
        break;
    }
    }
    assertNotNull(header);
    assertEquals("Subject", header.getName());
    assertEquals(header.getValue(), "test");
    */
    resultEndpoint.assertIsSatisfied();
}

From source file:edu.nyu.cs.omnidroid.app.controller.external.actions.GMailService.java

/**
 * Send a GMail//w  w w. j  av  a2s.  c  om
 */
private void send() {
    //Toast.makeText(this, "GMail Service Started", Toast.LENGTH_LONG).show();

    SMTPClient client = new SMTPClient("UTF-8");
    client.setDefaultTimeout(60 * 1000);

    client.setRequireStartTLS(true); // requires STARTTLS
    client.setUseAuth(true); // use SMTP AUTH

    try {
        client.connect("smtp.gmail.com", 587);
        checkReply(client);
    } catch (IOException e) {
        //ResultProcessor.process(this, intent, ResultProcessor.RESULT_FAILURE_INTERNET, 
        //   getString(R.string.gmail_failed_no_network));      
        return;
    }

    try {
        client.login("localhost", account.accountName, account.credential);
        checkReply(client);
    } catch (IOException e) {
        ResultProcessor.process(this, intent, ResultProcessor.RESULT_FAILURE_IRRECOVERABLE,
                getString(R.string.gmail_failed_authentication_error));
        return;
    }

    try {
        client.setSender(account.accountName);
        checkReply(client);

        client.addRecipient(to);
        checkReply(client);

        Writer writer = client.sendMessageData();

        if (writer != null) {
            SimpleSMTPHeader header = new SimpleSMTPHeader(account.accountName, to, subject);
            writer.write(header.toString());
            writer.write(body);
            writer.close();
            client.completePendingCommand();
            checkReply(client);
        }

        client.logout();
        client.disconnect();

    } catch (IOException e) {
        ResultProcessor.process(this, intent, ResultProcessor.RESULT_FAILURE_UNKNOWN,
                getString(R.string.gmail_failed_server_error));
        return;
    }
    ResultProcessor.process(this, intent, ResultProcessor.RESULT_SUCCESS, getString(R.string.gmail_sent));

}

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

/**
 * SMTP????????//from  w  w  w.j  a  v  a 2  s.  c o  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:me.schiz.jmeter.protocol.smtp.sampler.SMTPSampler.java

private SampleResult sampleConnect(SampleResult sr) {
    SMTPClient client;

    if (getUseSSL()) {
        client = new SMTPSClient(true);
    } else if (getUseSTARTTLS()) {
        client = new SMTPSClient(false);
    } else {/*  www.  jav  a 2  s.c  om*/
        client = new SMTPClient();
    }

    try {
        String request = "CONNECT \n";
        request += "Host : " + getHostname() + ":" + getPort() + "\n";
        request += "Default Timeout : " + getDefaultTimeout() + "\n";
        request += "Connect Timeout : " + getConnectionTimeout() + "\n";
        request += "So Timeout : " + getSoTimeout() + "\n";
        request += "Client : " + getClient() + "\n";
        if (getUseSSL())
            request += "SSL : true\n";
        else
            request += "SSL : false\n";
        if (getUseSTARTTLS())
            request += "STARTTLS : true\n";
        else
            request += "STARTTLS : false\n";

        sr.setRequestHeaders(request);
        sr.sampleStart();
        client.setDefaultTimeout(getDefaultTimeout());
        client.setConnectTimeout(getConnectionTimeout());
        client.connect(getHostname(), getPort());
        if (client.isConnected()) {
            SessionStorage.proto_type protoType = SessionStorage.proto_type.PLAIN;
            if (getUseSSL() && !getUseSTARTTLS())
                protoType = SessionStorage.proto_type.SSL;
            if (!getUseSSL() && getUseSTARTTLS())
                protoType = SessionStorage.proto_type.STARTTLS;

            SessionStorage.getInstance().putClient(getSOClient(), client, protoType);
            client.setSoTimeout(getSoTimeout());
            client.setTcpNoDelay(getTcpNoDelay());
            sr.setResponseCode(String.valueOf(client.getReplyCode()));
            sr.setResponseData(client.getReplyString().getBytes());
            setSuccessfulByResponseCode(sr, client.getReplyCode());
        }
    } catch (SocketException se) {
        sr.setResponseMessage(se.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(se.getClass().getName());
        log.error("client `" + client + "` ", se);
    } catch (IOException ioe) {
        sr.setResponseMessage(ioe.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(ioe.getClass().getName());
        log.error("client `" + client + "` ", ioe);
    }
    sr.sampleEnd();
    return sr;
}

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>/*from w ww .j  a v a 2s.c om*/
 */
@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.camel.component.james.smtp.SMTPTest.java

/**
 * Test send matching message.//from w  w w  .ja v a2s. 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.james.jmap.VacationRelayIntegrationTest.java

@Test
public void forwardingAnEmailShouldWork() throws Exception {
    jmapGuiceProbe.modifyVacation(AccountId.fromString(USER_WITH_DOMAIN),
            VacationPatch.builder().isEnabled(true).textBody(REASON).build());

    String externalMail = "ray@yopmail.com";

    SMTPClient smtpClient = new SMTPClient();
    smtpClient.connect(LOCALHOST_IP, SMTP_PORT);
    smtpClient.helo(DOMAIN);//from  w ww .  j a v a  2 s  . c  o m
    smtpClient.setSender(externalMail);
    smtpClient.rcpt("<" + USER_WITH_DOMAIN + ">");
    smtpClient.sendShortMessageData("content");

    calmlyAwait.atMost(1, TimeUnit.MINUTES).until(() -> {
        try {
            when().get("/api/email").then().statusCode(200).body("[0].from", equalTo(USER_WITH_DOMAIN))
                    .body("[0].to[0]", equalTo(externalMail)).body("[0].text", equalTo(REASON));

            return true;
        } catch (AssertionError e) {
            return false;
        }
    });
}

From source file:org.apache.james.mailets.utils.SMTPMessageSender.java

public static SMTPMessageSender noAuthentication(String ip, int port, String senderDomain) throws IOException {
    SMTPClient smtpClient = new SMTPClient();
    smtpClient.connect(ip, port);
    return new SMTPMessageSender(smtpClient, senderDomain);
}

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;/*ww  w .  jav  a2s . c o m*/
    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();
        }
    }

}