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.xiangzhurui.util.email.SMTPMail.java

public static void main(String[] args) {
    String sender, recipient, subject, filename, server, cc;
    List<String> ccList = new ArrayList<String>();
    BufferedReader stdin;/*from www.ja  v  a  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:examples.mail.java

public final static void main(String[] args) {
    String sender, recipient, subject, filename, server, cc;
    Vector ccList = new Vector();
    BufferedReader stdin;// w w  w.  j  a  va2s  . c o m
    FileReader fileReader = null;
    Writer writer;
    SimpleSMTPHeader header;
    SMTPClient client;
    Enumeration en;

    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();

            // Of course you don't want to do this because readLine() may be null
            cc = stdin.readLine().trim();

            if (cc.length() == 0)
                break;

            header.addCC(cc);
            ccList.addElement(cc);
        }

        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)));

        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);

        en = ccList.elements();

        while (en.hasMoreElements())
            client.addRecipient((String) en.nextElement());

        writer = client.sendMessageData();

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

        fileReader.close();

        client.logout();

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

From source file:com.Module.RegisterModule.java

public static boolean checkEmail(String email) {
    if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
        return false;
    }/*from  w  ww.  ja  v a2s  .com*/

    String host = "";
    String hostName = email.split("@")[1];
    Record[] result = null;
    SMTPClient client = new SMTPClient();

    try {
        // MX
        Lookup lookup = new Lookup(hostName, Type.MX);
        lookup.run();
        if (lookup.getResult() != Lookup.SUCCESSFUL) {
            return false;
        } else {
            result = lookup.getAnswers();
        }

        // ?
        for (int i = 0; i < result.length; i++) {
            host = result[i].getAdditionalName().toString();
            client.connect(host);
            if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
                client.disconnect();
                continue;
            } else {
                break;
            }
        }

        //2
        client.login("qq.com");
        client.setSender("526199427@163.com");
        client.addRecipient(email);
        if (250 == client.getReplyCode()) {
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            client.disconnect();
        } catch (IOException e) {
        }
    }
    return false;
}

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

/**
 * Check the response from the SMTP connection
 *//*from   w w  w  . j  a va2 s.  c  o m*/
private void checkReply(SMTPClient sc) throws IOException {
    if (SMTPReply.isNegativeTransient(sc.getReplyCode())) {
        sc.disconnect();
        throw new IOException("Transient SMTP error " + sc.getReplyCode());
    } else if (SMTPReply.isNegativePermanent(sc.getReplyCode())) {
        sc.disconnect();
        throw new IOException("Permanent SMTP error " + sc.getReplyCode());
    }
}

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

@SuppressWarnings("unchecked")
@Test/*  ww w  .  j  ava 2  s .  c o  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/*from w w w . j a va 2 s . c o  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:com.discursive.jccook.net.SMTPExample.java

public void start() throws SocketException, IOException {
    SMTPClient client = new SMTPClient();
    client.connect("www.discursive.com");
    int response = client.getReplyCode();
    if (SMTPReply.isPositiveCompletion(response)) {
        client.setSender("tobrien@discursive.com");
        client.addRecipient("tobrien@iesabroad.org");
        Writer message = client.sendMessageData();
        message.write("This is a test message");
        message.close();/*from   w ww.j a  v a 2s .  c o m*/
        boolean success = client.completePendingCommand();
        if (success) {
            System.out.println("Message sent");
        }
    } else {
        System.out.println("Error communicating with SMTP server");
    }
    client.disconnect();
}

From source file:emailchecker.CheckEmailObj.java

public boolean checkEmail(String email) {
    if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
        System.err.println("Format error");
        return false;
    }/*from w  w  w .j  ava  2s . c o  m*/

    //        String log = "";
    String host = "";
    String hostName = email.split("@")[1];
    Record[] result = null;
    SMTPClient client = new SMTPClient();

    try {
        // MX
        Lookup lookup = new Lookup(hostName, Type.MX);
        lookup.run();
        if (lookup.getResult() != Lookup.SUCCESSFUL) {
            log += "?MX\n";
            return false;
        } else {
            result = lookup.getAnswers();
        }

        // ?
        for (int i = 0; i < result.length; i++) {
            host = result[i].getAdditionalName().toString();
            client.connect(host);
            if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
                client.disconnect();
                continue;
            } else {
                log += "MX record about " + hostName + " exists.\n";
                log += "Connection succeeded to " + host + "\n";
                break;
            }
        }
        log += client.getReplyString();

        // HELO cyou-inc.com
        client.login("cyou-inc.com");
        log += ">HELO cyou-inc.com\n";
        log += "=" + client.getReplyString();

        // MAIL FROM: <zhaojinglun@cyou-inc.com>
        client.setSender("zhaojinglun@cyou-inc.com");
        log += ">MAIL FROM: <zhaojinglun@cyou-inc.com>\n";
        log += "=" + client.getReplyString();

        // RCPT TO: <$email>
        client.addRecipient(email);
        log += ">RCPT TO: <" + email + ">\n";
        log += "=" + client.getReplyString() + "\n\n";

        if (250 == client.getReplyCode()) {
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            client.disconnect();
        } catch (IOException e) {
        }
        // ?

        //  System.err.println(log);

    }
    return false;
}

From source file:me.schiz.jmeter.protocol.smtp.sampler.SMTPSampler.java

private SampleResult sampleDisconnect(SampleResult sr) {
    SocketClient soclient = SessionStorage.getInstance().getClient(getSOClient());
    SMTPClient client = null;
    if (soclient instanceof SMTPClient)
        client = (SMTPClient) soclient;/*  w w  w.j  ava  2 s .com*/

    String request = "DISCONNECT \n";
    request += "Client : " + getClient() + "\n";
    sr.setRequestHeaders(request);
    if (client == null) {
        clientNotFound(sr);
    } else {
        synchronized (client) {
            sr.sampleStart();
            try {
                client.disconnect();
                sr.setResponseCode(String.valueOf(client.getReplyCode()));
                setSuccessfulByResponseCode(sr, client.getReplyCode());
                SessionStorage.getInstance().removeClient(getSOClient());

            } catch (IOException e) {
                sr.setSuccessful(false);
                sr.setResponseData(e.toString().getBytes());
                sr.setResponseCode(e.getClass().getName());
                log.error("client `" + client + "` ", e);
                removeClient();
            }
            sr.sampleEnd();
        }
    }
    return sr;
}

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

/**
 * Send a GMail/* w  w w  .j  a v  a  2s.c  o  m*/
 */
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));

}