SMTPClient
Date: 2016-06-23

org.apache.commons.net.smtp

## Class SMTPClient

- java.lang.Object
- - org.apache.commons.net.SocketClient
  - - org.apache.commons.net.smtp.SMTP
    - - org.apache.commons.net.smtp.SMTPClient

- Direct Known Subclasses:
    SMTPSClient

      public class SMTPClient
      extends SMTP

  SMTPClient encapsulates all the functionality necessary to send files through an SMTP server. This class takes care of all low level details of interacting with an SMTP server and provides a convenient higher level interface. As with all classes derived from `SocketClient`, you must first connect to the server with `connect` before doing anything, and finally `disconnect` after you're completely finished interacting with the server. Then you need to check the SMTP reply code to see if the connection was successful. For example:

          try {
            int reply;
            client.connect("mail.foobar.com");
            System.out.print(client.getReplyString());

            // After connection attempt, you should check the reply code to verify
            // success.
            reply = client.getReplyCode();

            if(!SMTPReply.isPositiveCompletion(reply)) {
              client.disconnect();
              System.err.println("SMTP server refused connection.");
              System.exit(1);
            }

            // Do useful stuff here.
            ...
          } catch(IOException e) {
            if(client.isConnected()) {
              try {
                client.disconnect();
              } catch(IOException f) {
                // do nothing
              }
            }
            System.err.println("Could not connect to server.");
            e.printStackTrace();
            System.exit(1);
          }

  Immediately after connecting is the only real time you need to check the reply code (because connect is of type void). The convention for all the SMTP command methods in SMTPClient is such that they either return a boolean value or some other value. The boolean methods return true on a successful completion reply from the SMTP server and false on a reply resulting in an error condition or failure. The methods returning a value other than boolean return a value containing the higher level data produced by the SMTP command, or null if a reply resulted in an error condition or failure. If you want to access the exact SMTP reply code causing a success or failure, you must call `getReplyCode` after a success or failure.

  You should keep in mind that the SMTP server may choose to prematurely close a connection for various reasons. The SMTPClient class will detect a premature SMTP server connection closing when it receives a `SMTPReply.SERVICE_NOT_AVAILABLE` response to a command. When that occurs, the method encountering that reply will throw an `SMTPConnectionClosedException` . `SMTPConectionClosedException` is a subclass of `IOException` and therefore need not be caught separately, but if you are going to catch it separately, its catch block must appear before the more general `IOException` catch block. When you encounter an `SMTPConnectionClosedException` , you must disconnect the connection with `disconnect()` to properly clean up the system resources used by SMTPClient. Before disconnecting, you may check the last reply code and text with `getReplyCode` , `getReplyString` , and `getReplyStrings`.

  Rather than list it separately for each method, we mention here that every method communicating with the server and throwing an IOException can also throw a `MalformedServerReplyException` , which is a subclass of IOException. A MalformedServerReplyException will be thrown when the reply received from the server deviates enough from the protocol specification that it cannot be interpreted in a useful manner despite attempts to be as lenient as possible.

  See Also:
    `SMTP`, `SimpleSMTPHeader`, `RelayPath`, `SMTPConnectionClosedException`, `MalformedServerReplyException`

- - ### Field Summary

    - ### Fields inherited from class org.apache.commons.net.smtp.SMTP

      `_commandSupport_, DEFAULT_PORT, encoding`

    - ### Fields inherited from class org.apache.commons.net.SocketClient

      `_defaultPort_, _hostname_, _input_, _output_, _serverSocketFactory_, _socket_, _socketFactory_, _timeout_, connectTimeout, NETASCII_EOL`

  - ### Constructor Summary

    Constructors
    Constructor and Description
    `SMTPClient()` Default SMTPClient constructor.
    `SMTPClient(java.lang.String encoding)` Overloaded constructor that takes an encoding specification

  - ### Method Summary

    Methods
    Modifier and Type | Method and Description
    --- | ---
    `boolean` | `addRecipient(RelayPath path)` Add a recipient for a message using the SMTP RCPT command, specifying a forward relay path.
    `boolean` | `addRecipient(java.lang.String address)` Add a recipient for a message using the SMTP RCPT command, the recipient's email address.
    `boolean` | `completePendingCommand()` At least one SMTPClient method (`sendMessageData` ) does not complete the entire sequence of SMTP commands to complete a transaction.
    `java.lang.String` | `listHelp()` Fetches the system help information from the server and returns the full string.
    `java.lang.String` | `listHelp(java.lang.String command)` Fetches the help information for a given command from the server and returns the full string.
    `boolean` | `login()` Login to the SMTP server by sending the HELO command with the client hostname as an argument.
    `boolean` | `login(java.lang.String hostname)` Login to the SMTP server by sending the HELO command with the given hostname as an argument.
    `boolean` | `logout()` Logout of the SMTP server by sending the QUIT command.
    `boolean` | `reset()` Aborts the current mail transaction, resetting all server stored sender, recipient, and mail data, cleaing all buffers and tables.
    `java.io.Writer` | `sendMessageData()` Send the SMTP DATA command in preparation to send an email message.
    `boolean` | `sendNoOp()` Sends a NOOP command to the SMTP server.
    `boolean` | `sendShortMessageData(java.lang.String message)` A convenience method for sending short messages.
    `boolean` | `sendSimpleMessage(java.lang.String sender, java.lang.String[] recipients, java.lang.String message)` A convenience method for a sending short email without having to explicitly set the sender and recipient(s).
    `boolean` | `sendSimpleMessage(java.lang.String sender, java.lang.String recipient, java.lang.String message)` A convenience method for a sending short email without having to explicitly set the sender and recipient(s).
    `boolean` | `setSender(RelayPath path)` Set the sender of a message using the SMTP MAIL command, specifying a reverse relay path.
    `boolean` | `setSender(java.lang.String address)` Set the sender of a message using the SMTP MAIL command, specifying the sender's email address.
    `boolean` | `verify(java.lang.String username)` Verify that a username or email address is valid, i.e., that mail can be delivered to that mailbox on the server.

    - ### Methods inherited from class org.apache.commons.net.smtp.SMTP

      `_connectAction_, data, disconnect, expn, getCommandSupport, getReply, getReplyCode, getReplyString, getReplyStrings, helo, help, help, mail, noop, quit, rcpt, removeProtocolCommandistener, rset, saml, send, sendCommand, sendCommand, sendCommand, sendCommand, soml, turn, vrfy`

    - ### Methods inherited from class org.apache.commons.net.SocketClient

      `addProtocolCommandListener, connect, connect, connect, connect, connect, connect, createCommandSupport, fireCommandSent, fireReplyReceived, getCharset, getCharsetName, getConnectTimeout, getDefaultPort, getDefaultTimeout, getKeepAlive, getLocalAddress, getLocalPort, getProxy, getReceiveBufferSize, getRemoteAddress, getRemotePort, getSendBufferSize, getServerSocketFactory, getSoLinger, getSoTimeout, getTcpNoDelay, isAvailable, isConnected, removeProtocolCommandListener, setCharset, setConnectTimeout, setDefaultPort, setDefaultTimeout, setKeepAlive, setProxy, setReceiveBufferSize, setSendBufferSize, setServerSocketFactory, setSocketFactory, setSoLinger, setSoTimeout, setTcpNoDelay, verifyRemote`

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### Constructor Detail

    - #### SMTPClient

          public SMTPClient()

      Default SMTPClient constructor. Creates a new SMTPClient instance.

    - #### SMTPClient

          public SMTPClient(java.lang.String encoding)

      Overloaded constructor that takes an encoding specification
      Parameters:
        `encoding` - The encoding to use
      Since:
        2.0

  - ### Method Detail

    - #### completePendingCommand

          public boolean completePendingCommand()
                                         throws java.io.IOException

      At least one SMTPClient method (`sendMessageData` ) does not complete the entire sequence of SMTP commands to complete a transaction. These types of commands require some action by the programmer after the reception of a positive intermediate command. After the programmer's code completes its actions, it must call this method to receive the completion reply from the server and verify the success of the entire transaction.

      For example,

           writer = client.sendMessageData();
           if(writer == null) // failure
             return false;
           header =
            new SimpleSMTPHeader("foobar@foo.com", "foo@foobar.com", "Re: Foo");
           writer.write(header.toString());
           writer.write("This is just a test");
           writer.close();
           if(!client.completePendingCommand()) // failure
             return false;

      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### login

          public boolean login(java.lang.String hostname)
                        throws java.io.IOException

      Login to the SMTP server by sending the HELO 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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### login

          public boolean login()
                        throws java.io.IOException

      Login to the SMTP server by sending the HELO 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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### setSender

          public boolean setSender(RelayPath path)
                            throws java.io.IOException

      Set the sender of a message using the SMTP MAIL command, specifying a reverse relay path. The sender must be set first before any recipients may be specified, otherwise the mail server will reject your commands.

      Parameters:
        `path` - The reverse relay path pointing back to the sender.
      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### setSender

          public boolean setSender(java.lang.String address)
                            throws java.io.IOException

      Set the sender of a message using the SMTP MAIL command, specifying the sender's email address. The sender must be set first before any recipients may be specified, otherwise the mail server will reject your commands.

      Parameters:
        `address` - The sender's email address.
      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### addRecipient

          public boolean addRecipient(RelayPath path)
                               throws java.io.IOException

      Add a recipient for a message using the SMTP RCPT command, specifying a forward relay path. The sender must be set first before any recipients may be specified, otherwise the mail server will reject your commands.

      Parameters:
        `path` - The forward relay path pointing to the recipient.
      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### addRecipient

          public boolean addRecipient(java.lang.String address)
                               throws java.io.IOException

      Add a recipient for a message using the SMTP RCPT command, the recipient's email address. The sender must be set first before any recipients may be specified, otherwise the mail server will reject your commands.

      Parameters:
        `address` - The recipient's email address.
      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### sendMessageData

          public java.io.Writer sendMessageData()
                                         throws java.io.IOException

      Send the SMTP DATA command in preparation to send an email message. This method returns a DotTerminatedMessageWriter instance to which the message can be written. Null is returned if the DATA command fails.

      You must not issue any commands to the SMTP server (i.e., call any (other methods) until you finish writing to the returned Writer instance and close it. The SMTP protocol uses the same stream for issuing commands as it does for returning results. Therefore the returned Writer actually writes directly to the SMTP connection. After you close the writer, you can execute new commands. If you do not follow these requirements your program will not work properly.

      You can use the provided `SimpleSMTPHeader` class to construct a bare minimum header. To construct more complicated headers you should refer to RFC 5322. When the Java Mail API is finalized, you will be able to use it to compose fully compliant Internet text messages. The DotTerminatedMessageWriter takes care of doubling line-leading dots and ending the message with a single dot upon closing, so all you have to worry about is writing the header and the message.

      Upon closing the returned Writer, you need to call `completePendingCommand()` to finalize the transaction and verify its success or failure from the server reply.

      Returns:
        A DotTerminatedMessageWriter to which the message (including header) can be written. Returns null if the command fails.
      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
      See Also:
        `sendShortMessageData(String)`

    - #### sendShortMessageData

          public boolean sendShortMessageData(java.lang.String message)
                                       throws java.io.IOException

      A convenience method for sending short messages. This method fetches the Writer returned by `sendMessageData()` and writes the specified String to it. After writing the message, this method calls `completePendingCommand()` to finalize the transaction and returns its success or failure.

      Parameters:
        `message` - The short email message to send. This must include the headers and the body, but not the trailing "."
      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### sendSimpleMessage

          public boolean sendSimpleMessage(java.lang.String sender,
                                  java.lang.String recipient,
                                  java.lang.String message)
                                    throws java.io.IOException

      A convenience method for a sending short email without having to explicitly set the sender and recipient(s). This method sets the sender and recipient using `setSender` and `addRecipient` , and then sends the message using `sendShortMessageData` .

      Parameters:
        `sender` - The email address of the sender.
        `recipient` - The email address of the recipient.
        `message` - The short email message to send. This must include the headers and the body, but not the trailing "."
      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### sendSimpleMessage

          public boolean sendSimpleMessage(java.lang.String sender,
                                  java.lang.String[] recipients,
                                  java.lang.String message)
                                    throws java.io.IOException

      A convenience method for a sending short email without having to explicitly set the sender and recipient(s). This method sets the sender and recipients using `setSender` and `addRecipient`, and then sends the message using `sendShortMessageData`.

      Note that the method ignores failures when calling `addRecipient` so long as at least one call succeeds. If no recipients can be successfully added then the method will fail (and does not attempt to send the message)

      Parameters:
        `sender` - The email address of the sender.
        `recipients` - An array of recipient email addresses.
        `message` - The short email message to send. This must include the headers and the body, but not the trailing "."
      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### logout

          public boolean logout()
                         throws java.io.IOException

      Logout of the SMTP server by sending the QUIT command.

      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### reset

          public boolean reset()
                        throws java.io.IOException

      Aborts the current mail transaction, resetting all server stored sender, recipient, and mail data, cleaing all buffers and tables.

      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### verify

          public boolean verify(java.lang.String username)
                         throws java.io.IOException

      Verify that a username or email address is valid, i.e., that mail can be delivered to that mailbox on the server.

      Parameters:
        `username` - The username or email address to validate.
      Returns:
        True if the username is valid, 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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### listHelp

          public java.lang.String listHelp()
                                    throws java.io.IOException

      Fetches the system help information from the server and returns the full string.

      Returns:
        The system help string obtained from the server. null if the information could not be obtained.
      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### listHelp

          public java.lang.String listHelp(java.lang.String command)
                                    throws java.io.IOException

      Fetches the help information for a given command from the server and returns the full string.

      Parameters:
        `command` - The command on which to ask for help.
      Returns:
        The command help string obtained from the server. null if the information could not be obtained.
      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.

    - #### sendNoOp

          public boolean sendNoOp()
                           throws java.io.IOException

      Sends a NOOP command to the SMTP server. This is useful for preventing server timeouts.

      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.
        `java.io.IOException` - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.