Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.apache.commons.net.smtp;
 
 
 import  org.apache.commons.net.util.Base64;


An SMTP Client class with authentication support (RFC4954).

Since:
3.0
See also:
SMTPClient
 
 public class AuthenticatingSMTPClient extends SMTPSClient
 {
    
The default AuthenticatingSMTPClient constructor. Creates a new Authenticating SMTP Client.

Throws:
NoSuchAlgorithmException
 
     {
         super();
     }

    
Overloaded constructor that takes a protocol specification

Parameters:
protocol The protocol to use
Throws:
NoSuchAlgorithmException
 
     public AuthenticatingSMTPClient(String protocolthrows NoSuchAlgorithmException {
         super(protocol);
     }

    
Overloaded constructor that takes a protocol specification and the implicit argument

Parameters:
proto the protocol.
implicit The security mode, true for implicit, false for explicit
Since:
3.3
 
     public AuthenticatingSMTPClient(String protoboolean implicit)
     {
       super(protoimplicit);
     }

    
Overloaded constructor that takes the protocol specification, the implicit argument and encoding

Parameters:
proto the protocol.
implicit The security mode, true for implicit, false for explicit
encoding the encoding
Since:
3.3
 
     public AuthenticatingSMTPClient(String protoboolean implicitString encoding)
     {
       super(protoimplicitencoding);
     }

    
Overloaded constructor that takes the implicit argument, and using DEFAULT_PROTOCOL i.e. TLS

Parameters:
implicit The security mode, true for implicit, false for explicit
ctx A pre-configured SSL Context.
Since:
3.3
 
     public AuthenticatingSMTPClient(boolean implicitSSLContext ctx)
     {
       super(implicitctx);
     }

    
Overloaded constructor that takes a protocol specification and encoding

Parameters:
protocol The protocol to use
encoding The encoding to use
Throws:
NoSuchAlgorithmException
Since:
3.3
 
    public AuthenticatingSMTPClient(String protocolString encodingthrows NoSuchAlgorithmException {
        super(protocolfalseencoding);
    }

    
A convenience method to send the ESMTP EHLO command to the server, receive the reply, and return the reply code.

Parameters:
hostname The hostname of the sender.
Returns:
The reply code received from the server.
Throws:
SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send SMTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending the command or receiving the server reply.
    public int ehlo(String hostnamethrows IOException
    {
        return sendCommand(.hostname);
    }

    
Login to the ESMTP server by sending the EHLO command with the given hostname as an argument. Before performing any mail commands, you must first login.

Parameters:
hostname The hostname with which to greet the SMTP server.
Returns:
True if successfully completed, false if not.
Throws:
SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send SMTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean elogin(String hostnamethrows IOException
    {
        return SMTPReply.isPositiveCompletion(ehlo(hostname));
    }


    
Login to the ESMTP server by sending the EHLO command with the client hostname as an argument. Before performing any mail commands, you must first login.

Returns:
True if successfully completed, false if not.
Throws:
SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send SMTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    public boolean elogin() throws IOException
    {
        String name;
        InetAddress host;
        host = getLocalAddress();
        name = host.getHostName();
        if (name == null) {
            return false;
        }
        return SMTPReply.isPositiveCompletion(ehlo(name));
    }

    
Returns the integer values of the enhanced reply code of the last SMTP reply.

Returns:
The integer values of the enhanced reply code of the last SMTP reply. First digit is in the first array element.
    public int[] getEnhancedReplyCode()
    {
        String reply = getReplyString().substring(4);
        String[] parts = reply.substring(0, reply.indexOf(' ')).split ("\\.");
        int[] res = new int[parts.length];
        for (int i = 0; i < parts.lengthi++)
        {
            res[i] = Integer.parseInt (parts[i]);
        }
        return res;
    }

    
Authenticate to the SMTP server by sending the AUTH command with the selected mechanism, using the given username and the given password.

Parameters:
method the method to use, one of the AuthenticatingSMTPClient.AUTH_METHOD enum values
username the user name. If the method is XOAUTH, then this is used as the plain text oauth protocol parameter string which is Base64-encoded for transmission.
password the password for the username. Ignored for XOAUTH.
Returns:
True if successfully completed, false if not.
Throws:
SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send SMTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
NoSuchAlgorithmException If the CRAM hash algorithm cannot be instantiated by the Java runtime system.
InvalidKeyException If the CRAM hash algorithm failed to use the given password.
InvalidKeySpecException If the CRAM hash algorithm failed to use the given password.
    public boolean auth(AuthenticatingSMTPClient.AUTH_METHOD method,
                        String usernameString password)
                        throws IOExceptionNoSuchAlgorithmException,
                        InvalidKeyExceptionInvalidKeySpecException
    {
        if (!SMTPReply.isPositiveIntermediate(sendCommand(.,
                AUTH_METHOD.getAuthName(method)))) {
            return false;
        }
        if (method.equals(.))
        {
            // the server sends an empty response ("334 "), so we don't have to read it.
            return SMTPReply.isPositiveCompletion(sendCommand(
                    Base64.encodeBase64StringUnChunked(("\000" + username + "\000" + password).getBytes(getCharsetName())) // Java 1.6 can use getCharset()
                ));
        }
        else if (method.equals(.))
        {
            // get the CRAM challenge
            byte[] serverChallenge = Base64.decodeBase64(getReplyString().substring(4).trim());
            // get the Mac instance
            Mac hmac_md5 = Mac.getInstance("HmacMD5");
            hmac_md5.init(new SecretKeySpec(password.getBytes(getCharsetName()), "HmacMD5")); // Java 1.6 can use getCharset()
            // compute the result:
            byte[] hmacResult = _convertToHexString(hmac_md5.doFinal(serverChallenge)).getBytes(getCharsetName()); // Java 1.6 can use getCharset()
            // join the byte arrays to form the reply
            byte[] usernameBytes = username.getBytes(getCharsetName()); // Java 1.6 can use getCharset()
            byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length];
            System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length);
            toEncode[usernameBytes.length] = ' ';
            System.arraycopy(hmacResult, 0, toEncodeusernameBytes.length + 1, hmacResult.length);
            // send the reply and read the server code:
            return SMTPReply.isPositiveCompletion(sendCommand(
                Base64.encodeBase64StringUnChunked(toEncode)));
        }
        else if (method.equals(.))
        {
            // the server sends fixed responses (base64("Username") and
            // base64("Password")), so we don't have to read them.
            if (!SMTPReply.isPositiveIntermediate(sendCommand(
                Base64.encodeBase64StringUnChunked(username.getBytes(getCharsetName()))))) { // Java 1.6 can use getCharset()
                return false;
            }
            return SMTPReply.isPositiveCompletion(sendCommand(
                Base64.encodeBase64StringUnChunked(password.getBytes(getCharsetName())))); // Java 1.6 can use getCharset()
        }
        else if (method.equals(.))
        {
            return SMTPReply.isPositiveIntermediate(sendCommand(
                    Base64.encodeBase64StringUnChunked(username.getBytes(getCharsetName())) // Java 1.6 can use getCharset()
            ));
        } else {
            return false// safety check
        }
    }

    
Converts the given byte array to a String containing the hex values of the bytes. For example, the byte 'A' will be converted to '41', because this is the ASCII code (and the byte value) of the capital letter 'A'.

Parameters:
a The byte array to convert.
Returns:
The resulting String of hex codes.
    private String _convertToHexString(byte[] a)
    {
        StringBuilder result = new StringBuilder(a.length*2);
        for (byte element : a)
        {
            if ( (element & 0x0FF) <= 15 ) {
                result.append("0");
            }
            result.append(Integer.toHexString(element & 0x0FF));
        }
        return result.toString();
    }

    
The enumeration of currently-supported authentication methods.
    public static enum AUTH_METHOD
    {
        
The standarised (RFC4616) PLAIN method, which sends the password unencrypted (insecure).
        PLAIN,
        
The standarised (RFC2195) CRAM-MD5 method, which doesn't send the password (secure).
        CRAM_MD5,
        
The unstandarised Microsoft LOGIN method, which sends the password unencrypted (insecure).
        LOGIN,
        
XOAuth method which accepts a signed and base64ed OAuth URL.
        XOAUTH;

        
Gets the name of the given authentication method suitable for the server.

Parameters:
method The authentication method to get the name for.
Returns:
The name of the given authentication method suitable for the server.
        public static final String getAuthName(AUTH_METHOD method)
        {
            if (method.equals(.)) {
                return "PLAIN";
            } else if (method.equals(.)) {
                return "CRAM-MD5";
            } else if (method.equals(.)) {
                return "LOGIN";
            } else if (method.equals(.)) {
                return "XOAUTH";
            } else {
                return null;
            }
        }
    }
/* kate: indent-width 4; replace-tabs on; */
New to GrepCode? Check out our FAQ X