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) throws SocketException, IOException 

Source Link

Document

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

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;//ww  w  . java2 s  .c  om
    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;/*  www .j  a v a  2  s .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;
    }// w w w. j a va2s .c o  m

    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: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();//  w  w w .  ja 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:com.discursive.jccook.xml.bean.EmailRule.java

public void end() throws Exception {
    Message message = (Message) digester.getRoot();

    SMTPClient client = new SMTPClient();
    client.connect("www.discursive.com");
    client.sendSimpleMessage(from, to, message.getText());
}

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.  ja  v  a  2  s  .c  om

    //        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:autohit.call.modules.SimpleSmtpModule.java

/**
 * Start method. It will open a connection to an SMTP server/relay. If a
 * session is already started, it will report an error. If it cannot make
 * the connection, it will cause a fault.
 * //from w w w.  j av a  2s . c om
 * @param addr
 *           the domain name address. Do not include protocol or port.
 * @param post
 *           this should be a parsable integer. If it is null, the default
 *           will be used.
 * @throws CallException
 */
private void start(String addr, String port) throws CallException {

    SMTPClient candidate = null;

    // Already started?
    if (client != null) {
        this.error("Session already started.  Ignoring new start().");
        return;
    }
    // Passed a port number?
    int portNum = 0;
    if (port != null) {
        try {
            portNum = Integer.parseInt(port);
        } catch (Exception e) {
            this.fault("Malformed 'port' number.  It must be a parsable integer.  text=" + port);
        }
    }
    // Try and construct it
    try {
        candidate = new SMTPClient();
        if (port == null) {
            candidate.connect(addr);
        } else {
            candidate.connect(addr, portNum);
        }

    } catch (Exception ex) {
        if (client.isConnected()) {
            try {
                client.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        this.fault("Could not connect to host.  message=" + ex.getMessage());
    }

    // NO CODE AFTER THIS!
    this.log("Connection started.");
    client = candidate;
}

From source file:autohit.call.modules.TolerantSmtpModule.java

/**
 * Start method. It will open a connection to an SMTP server/relay. If a
 * session is already started, it will report an error. If it cannot make
 * the connection, it will cause a fault.
 * /*  w ww .  j  a v a 2s. co  m*/
 * @param addr
 *            the domain name address. Do not include protocol or port.
 * @param post
 *            this should be a parsable integer. If it is null, the default
 *            will be used.
 * @throws CallException
 */
private void start(String addr, String port) throws CallException {

    SMTPClient candidate = null;

    // Already started?
    if (client != null) {
        this.error("Session already started.  Ignoring new start().");
        return;
    }
    // Passed a port number?
    int portNum = 0;
    if (port != null) {
        try {
            portNum = Integer.parseInt(port);
        } catch (Exception e) {
            this.fault("Malformed 'port' number.  It must be a parsable integer.  text=" + port);
        }
    }
    // Try and construct it
    try {
        candidate = new SMTPClient();
        if (port == null) {
            candidate.connect(addr);
        } else {
            candidate.connect(addr, portNum);
        }

    } catch (Exception ex) {
        this.error("Could not connect to host.  message=" + ex.getMessage());
        return;
    }

    // NO CODE AFTER THIS!
    this.log("Connection started.");
    loggedIn = false;
    client = candidate;
}

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

/**
 * Send the soap request message to the server
 *
 * @param msgContext message context/*from   ww  w  .  j  av a2 s .  com*/
 *
 * @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 ww  w.j  a v a 2s  .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();
}