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

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

Introduction

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

Prototype

public boolean login(String hostname) throws IOException 

Source Link

Document

Login to the SMTP server by sending the HELO command with the given hostname as an argument.

Usage

From source file:com.Module.RegisterModule.java

public static boolean checkEmail(String email) {
    if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
        return false;
    }//from   www  .  j av a 2s.  c  om

    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: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 a  v a 2 s .  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: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 w w  .j  a  v  a2s. com*/
 */
@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 v a 2s  .  co m*/
 *
 * @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
 * /* w ww  .  j  a va  2s.  c om*/
 * @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();
}