public class

SMTPTransport

extends Transport
java.lang.Object
   ↳ com.google.code.javax.mail.Service
     ↳ com.google.code.javax.mail.Transport
       ↳ com.google.code.com.sun.mail.smtp.SMTPTransport
Known Direct Subclasses

Class Overview

This class implements the Transport abstract class using SMTP for message submission and transport.

See the com.sun.mail.smtp package documentation for further information on the SMTP protocol provider.

This class includes many protected methods that allow a subclass to extend this class and add support for non-standard SMTP commands. The issueCommand(String, int) and sendCommand(String) methods can be used to send simple SMTP commands. Other methods such as the mailFrom() and data() methods can be overridden to insert new commands before or after the corresponding SMTP commands. For example, a subclass could do this to send the XACT command before sending the DATA command:

	protected OutputStream data() throws MessagingException {
	    if (supportsExtension("XACCOUNTING"))
	        issueCommand("XACT", 25);
	    return super.data();
	}
 

See Also
  • javax.mail.event.ConnectionEvent
  • javax.mail.event.TransportEvent

Summary

Constants
String UNKNOWN
Fields
private static final byte[] CRLF
private static final String[] UNKNOWN_SA
private Address[] addresses
private Map authenticators
private String authorizationID
private SMTPOutputStream dataStream
private String defaultAuthenticationMechanisms
private int defaultPort
private boolean enableSASL
private MessagingException exception
private Hashtable extMap
private static char[] hexchar
private String host
private static final String[] ignoreList Headers that should not be included when sending
private Address[] invalidAddr
private boolean isSSL
private int lastReturnCode
private String lastServerResponse
private LineInputStream lineInputStream
private String localHostName
private MimeMessage message
private String name
private boolean noopStrict
private boolean notificationDone
private String ntlmDomain
private PrintStream out
private boolean quitWait
private boolean reportSuccess
private boolean requireStartTLS
private SaslAuthenticator saslAuthenticator
private String[] saslMechanisms
private String saslRealm
private boolean sendPartiallyFailed
private BufferedInputStream serverInput
private OutputStream serverOutput
private Socket serverSocket
private boolean useRset
private boolean useStartTLS
private Address[] validSentAddr
private Address[] validUnsentAddr
[Expand]
Inherited Fields
From class com.google.code.javax.mail.Transport
From class com.google.code.javax.mail.Service
Public Constructors
SMTPTransport(Session session, URLName urlname)
Constructor that takes a Session object and a URLName that represents a specific SMTP server.
Protected Constructors
SMTPTransport(Session session, URLName urlname, String name, boolean isSSL)
Constructor used by this class and by SMTPSSLTransport subclass.
Public Methods
synchronized void close()
Close the Transport and terminate the connection to the server.
synchronized void connect(Socket socket)
Start the SMTP protocol on the given socket, which was already connected by the caller.
synchronized String getAuthorizationId()
Gets the authorization ID to be used for authentication.
String getExtensionParameter(String ext)
Return the parameter the server provided for the specified service extension, or null if the extension isn't supported.
synchronized int getLastReturnCode()
Return the return code from the last response we got from the server.
synchronized String getLastServerResponse()
Return the last response we got from the server.
synchronized String getLocalHost()
Get the name of the local host, for use in the EHLO and HELO commands.
synchronized String getNTLMDomain()
Gets the NTLM domain to be used for NTLM authentication.
synchronized boolean getNoopStrict()
Is the NOOP command required to return a response code of 250 to indicate success?
synchronized boolean getReportSuccess()
Should we report even successful sends by throwing an exception? If so, a SendFailedException will always be thrown and an com.sun.mail.smtp.SMTPAddressSucceededException SMTPAddressSucceededException will be included in the exception chain for each successful address, along with the usual com.sun.mail.smtp.SMTPAddressFailedException SMTPAddressFailedException for each unsuccessful address.
synchronized boolean getRequireStartTLS()
Should we require the STARTTLS command to secure the connection?
synchronized boolean getSASLEnabled()
Is SASL authentication enabled?
synchronized String[] getSASLMechanisms()
Get the list of SASL mechanisms to consider if SASL authentication is enabled.
synchronized String getSASLRealm()
Gets the SASL realm to be used for DIGEST-MD5 authentication.
synchronized boolean getStartTLS()
Should we use the STARTTLS command to secure the connection if the server supports it?
synchronized boolean getUseRset()
Should we use the RSET command instead of the NOOP command in the @{link #isConnected isConnected} method?
synchronized boolean isConnected()
Check whether the transport is connected.
synchronized void issueCommand(String cmd, int expect)
Send the command to the server.
boolean sasllogin(String[] allowed, String realm, String authzid, String u, String p)
SASL-based login.
synchronized void sendMessage(Message message, Address[] addresses)
Send the Message to the specified list of addresses.
synchronized void setAuthorizationID(String authzid)
Sets the authorization ID to be used for authentication.
synchronized void setLocalHost(String localhost)
Set the name of the local host, for use in the EHLO and HELO commands.
synchronized void setNTLMDomain(String ntlmDomain)
Sets the NTLM domain to be used for NTLM authentication.
synchronized void setNoopStrict(boolean noopStrict)
Set whether the NOOP command is required to return a response code of 250 to indicate success.
synchronized void setReportSuccess(boolean reportSuccess)
Set whether successful sends should be reported by throwing an exception.
synchronized void setRequireStartTLS(boolean requireStartTLS)
Set whether the STARTTLS command should be required.
synchronized void setSASLEnabled(boolean enableSASL)
Set whether SASL authentication is enabled.
synchronized void setSASLMechanisms(String[] mechanisms)
Set the list of SASL mechanisms to consider if SASL authentication is enabled.
synchronized void setSASLRealm(String saslRealm)
Sets the SASL realm to be used for DIGEST-MD5 authentication.
synchronized void setStartTLS(boolean useStartTLS)
Set whether the STARTTLS command should be used.
synchronized void setUseRset(boolean useRset)
Set whether the RSET command should be used instead of the NOOP command in the @{link #isConnected isConnected} method.
synchronized int simpleCommand(String cmd)
Send the command to the server and return the response code from the server.
boolean supportsExtension(String ext)
Return true if the SMTP server supports the specified service extension.
Protected Methods
void checkConnected()
Check if we're in the connected state.
OutputStream data()
Send the DATA command to the SMTP host and return an OutputStream to which the data is to be written.
boolean ehlo(String domain)
Issue the EHLO command.
void finalize()
Stop the event dispatcher thread so the queue can be garbage collected.
void finishData()
Terminate the sent data.
void helo(String domain)
Issue the HELO command.
void mailFrom()
Issue the MAIL FROM: command to start sending a message.
void notifyTransportListeners(int type, Address[] validSent, Address[] validUnsent, Address[] invalid, Message msg)
Notify all TransportListeners.
boolean protocolConnect(String host, int port, String user, String passwd)
Performs the actual protocol-specific connection attempt.
void rcptTo()
Sends each address to the SMTP host using the RCPT TO: command and copies the address either into the validSentAddr or invalidAddr arrays.
int readServerResponse()
Reads server reponse returning the returnCode as the number.
void sendCommand(String cmd)
Sends command cmd to the server terminating it with CRLF.
int simpleCommand(byte[] cmd)
Send the command to the server and return the response code from the server.
void startTLS()
Issue the STARTTLS command and switch the socket to TLS mode if it succeeds.
boolean supportsAuthentication(String auth)
Does the server we're connected to support the specified authentication mechanism? Uses the extension information returned by the server from the EHLO command.
static String xtext(String s)
Convert a string to RFC 1891 xtext format.
[Expand]
Inherited Methods
From class com.google.code.javax.mail.Transport
From class com.google.code.javax.mail.Service
From class java.lang.Object

Constants

private static final String UNKNOWN

Constant Value: "UNKNOWN"

Fields

private static final byte[] CRLF

private static final String[] UNKNOWN_SA

private Address[] addresses

private Map authenticators

private String authorizationID

private SMTPOutputStream dataStream

private String defaultAuthenticationMechanisms

private int defaultPort

private boolean enableSASL

private MessagingException exception

private Hashtable extMap

private static char[] hexchar

private String host

private static final String[] ignoreList

Headers that should not be included when sending

private Address[] invalidAddr

private boolean isSSL

private int lastReturnCode

private String lastServerResponse

private LineInputStream lineInputStream

private String localHostName

private MimeMessage message

private String name

private boolean noopStrict

private boolean notificationDone

private String ntlmDomain

private PrintStream out

private boolean quitWait

private boolean reportSuccess

private boolean requireStartTLS

private SaslAuthenticator saslAuthenticator

private String[] saslMechanisms

private String saslRealm

private boolean sendPartiallyFailed

private BufferedInputStream serverInput

private OutputStream serverOutput

private Socket serverSocket

private boolean useRset

private boolean useStartTLS

private Address[] validSentAddr

private Address[] validUnsentAddr

Public Constructors

public SMTPTransport (Session session, URLName urlname)

Constructor that takes a Session object and a URLName that represents a specific SMTP server.

Parameters
session
urlname

Protected Constructors

protected SMTPTransport (Session session, URLName urlname, String name, boolean isSSL)

Constructor used by this class and by SMTPSSLTransport subclass.

Parameters
session
urlname
name
isSSL

Public Methods

public synchronized void close ()

Close the Transport and terminate the connection to the server.

public synchronized void connect (Socket socket)

Start the SMTP protocol on the given socket, which was already connected by the caller. Useful for implementing the SMTP ATRN command (RFC 2645) where an existing connection is used when the server reverses roles and becomes the client.

Parameters
socket

public synchronized String getAuthorizationId ()

Gets the authorization ID to be used for authentication.

Returns
  • the authorization ID to use for authentication.

public String getExtensionParameter (String ext)

Return the parameter the server provided for the specified service extension, or null if the extension isn't supported.

Parameters
ext The service extension name
Returns
  • the extension parameter

public synchronized int getLastReturnCode ()

Return the return code from the last response we got from the server.

Returns
  • return code from last response from server

public synchronized String getLastServerResponse ()

Return the last response we got from the server. A failed send is often followed by an RSET command, but the response from the RSET command is not saved. Instead, this returns the response from the command before the RSET command.

Returns
  • last response from server

public synchronized String getLocalHost ()

Get the name of the local host, for use in the EHLO and HELO commands. The property mail.smtp.localhost overrides mail.smtp.localaddress, which overrides what InetAddress would tell us.

public synchronized String getNTLMDomain ()

Gets the NTLM domain to be used for NTLM authentication.

Returns
  • the name of the domain to use for NTLM authentication.

public synchronized boolean getNoopStrict ()

Is the NOOP command required to return a response code of 250 to indicate success?

Returns
  • true if NOOP must return 250

public synchronized boolean getReportSuccess ()

Should we report even successful sends by throwing an exception? If so, a SendFailedException will always be thrown and an com.sun.mail.smtp.SMTPAddressSucceededException SMTPAddressSucceededException will be included in the exception chain for each successful address, along with the usual com.sun.mail.smtp.SMTPAddressFailedException SMTPAddressFailedException for each unsuccessful address.

Returns
  • true if an exception will be thrown on successful sends.

public synchronized boolean getRequireStartTLS ()

Should we require the STARTTLS command to secure the connection?

Returns
  • true if the STARTTLS command will be required

public synchronized boolean getSASLEnabled ()

Is SASL authentication enabled?

Returns
  • true if SASL authentication is enabled

public synchronized String[] getSASLMechanisms ()

Get the list of SASL mechanisms to consider if SASL authentication is enabled. If the list is empty or null, all available SASL mechanisms are considered.

Returns
  • the array of SASL mechanisms to consider

public synchronized String getSASLRealm ()

Gets the SASL realm to be used for DIGEST-MD5 authentication.

Returns
  • the name of the realm to use for SASL authentication.

public synchronized boolean getStartTLS ()

Should we use the STARTTLS command to secure the connection if the server supports it?

Returns
  • true if the STARTTLS command will be used

public synchronized boolean getUseRset ()

Should we use the RSET command instead of the NOOP command in the @{link #isConnected isConnected} method?

Returns
  • true if RSET will be used

public synchronized boolean isConnected ()

Check whether the transport is connected. Override superclass method, to actually ping our server connection.

Returns
  • true if the service is connected, false if it is not connected

public synchronized void issueCommand (String cmd, int expect)

Send the command to the server. If the expected response code is not received, throw a MessagingException.

Parameters
cmd The command to send
expect The expected response code (-1 means don't care)

public boolean sasllogin (String[] allowed, String realm, String authzid, String u, String p)

SASL-based login.

Parameters
allowed
realm
authzid
u
p

public synchronized void sendMessage (Message message, Address[] addresses)

Send the Message to the specified list of addresses.

If all the addresses succeed the SMTP check using the RCPT TO: command, we attempt to send the message. A TransportEvent of type MESSAGE_DELIVERED is fired indicating the successful submission of a message to the SMTP host.

If some of the addresses fail the SMTP check, and the mail.stmp.sendpartial property is not set, sending is aborted. The TransportEvent of type MESSAGE_NOT_DELIVERED is fired containing the valid and invalid addresses. The SendFailedException is also thrown.

If some of the addresses fail the SMTP check, and the mail.stmp.sendpartial property is set to true, the message is sent. The TransportEvent of type MESSAGE_PARTIALLY_DELIVERED is fired containing the valid and invalid addresses. The SMTPSendFailedException is also thrown.

MessagingException is thrown if the message can't write out an RFC822-compliant stream using its writeTo method.

Parameters
message The MimeMessage to be sent
addresses List of addresses to send this message to
Throws
SMTPSendFailedException if the send failed because of an SMTP command error
SendFailedException if the send failed because of invalid addresses.
MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage.
See Also
  • javax.mail.event.TransportEvent

public synchronized void setAuthorizationID (String authzid)

Sets the authorization ID to be used for authentication.

Parameters
authzid The authorization ID to use for authentication.

public synchronized void setLocalHost (String localhost)

Set the name of the local host, for use in the EHLO and HELO commands.

Parameters
localhost

public synchronized void setNTLMDomain (String ntlmDomain)

Sets the NTLM domain to be used for NTLM authentication.

Parameters
ntlmDomain The name of the domain to use for NTLM authentication.

public synchronized void setNoopStrict (boolean noopStrict)

Set whether the NOOP command is required to return a response code of 250 to indicate success.

Parameters
noopStrict Is NOOP required to return 250?

public synchronized void setReportSuccess (boolean reportSuccess)

Set whether successful sends should be reported by throwing an exception.

Parameters
reportSuccess Should we throw an exception on success?

public synchronized void setRequireStartTLS (boolean requireStartTLS)

Set whether the STARTTLS command should be required.

Parameters
requireStartTLS Should we require the STARTTLS command?

public synchronized void setSASLEnabled (boolean enableSASL)

Set whether SASL authentication is enabled.

Parameters
enableSASL Should we enable SASL authentication?

public synchronized void setSASLMechanisms (String[] mechanisms)

Set the list of SASL mechanisms to consider if SASL authentication is enabled. If the list is empty or null, all available SASL mechanisms are considered.

Parameters
mechanisms The array of SASL mechanisms to consider

public synchronized void setSASLRealm (String saslRealm)

Sets the SASL realm to be used for DIGEST-MD5 authentication.

Parameters
saslRealm The name of the realm to use for SASL authentication.

public synchronized void setStartTLS (boolean useStartTLS)

Set whether the STARTTLS command should be used.

Parameters
useStartTLS Should we use the STARTTLS command?

public synchronized void setUseRset (boolean useRset)

Set whether the RSET command should be used instead of the NOOP command in the @{link #isConnected isConnected} method.

Parameters
useRset Should we use the RSET command?

public synchronized int simpleCommand (String cmd)

Send the command to the server and return the response code from the server.

Parameters
cmd

public boolean supportsExtension (String ext)

Return true if the SMTP server supports the specified service extension. Extensions are reported as results of the EHLO command when connecting to the server. See RFC 1869 and other RFCs that define specific extensions.

Parameters
ext The service extension name
Returns
  • true if the extension is supported

Protected Methods

protected void checkConnected ()

Check if we're in the connected state. Don't bother checking whether the server is still alive, that will be detected later.

Throws
IllegalStateException if not connected

protected OutputStream data ()

Send the DATA command to the SMTP host and return an OutputStream to which the data is to be written.

protected boolean ehlo (String domain)

Issue the EHLO command. Collect the returned list of service extensions.

Parameters
domain Our domain
Returns
  • true if command succeeds

protected void finalize ()

Stop the event dispatcher thread so the queue can be garbage collected.

Throws
Throwable

protected void finishData ()

Terminate the sent data.

Throws
IOException
MessagingException

protected void helo (String domain)

Issue the HELO command.

Parameters
domain Our domain

protected void mailFrom ()

Issue the MAIL FROM: command to start sending a message.

Gets the sender's address in the following order:

  1. SMTPMessage.getEnvelopeFrom()
  2. mail.smtp.from property
  3. From: header in the message
  4. System username using the InternetAddress.getLocalAddress() method

protected void notifyTransportListeners (int type, Address[] validSent, Address[] validUnsent, Address[] invalid, Message msg)

Notify all TransportListeners. Keep track of whether notification has been done so as to only notify once per send.

Parameters
type
validSent
validUnsent
invalid
msg

protected boolean protocolConnect (String host, int port, String user, String passwd)

Performs the actual protocol-specific connection attempt. Will attempt to connect to "localhost" if the host was null.

Unless mail.smtp.ehlo is set to false, we'll try to identify ourselves using the ESMTP command EHLO. If mail.smtp.auth is set to true, we insist on having a username and password, and will try to authenticate ourselves if the server supports the AUTH extension (RFC 2554).

Parameters
host The name of the host to connect to
port The port to use (-1 means use default port)
user The name of the user to login as
passwd The user's password
Returns
  • true if connection successful, false if authentication failed
Throws
MessagingException for non-authentication failures

protected void rcptTo ()

Sends each address to the SMTP host using the RCPT TO: command and copies the address either into the validSentAddr or invalidAddr arrays. Sets the sendFailed flag to true if any addresses failed.

protected int readServerResponse ()

Reads server reponse returning the returnCode as the number. Returns -1 on failure. Sets lastServerResponse and lastReturnCode.

Returns
  • server response code

protected void sendCommand (String cmd)

Sends command cmd to the server terminating it with CRLF.

Parameters
cmd

protected int simpleCommand (byte[] cmd)

Send the command to the server and return the response code from the server.

Parameters
cmd

protected void startTLS ()

Issue the STARTTLS command and switch the socket to TLS mode if it succeeds.

protected boolean supportsAuthentication (String auth)

Does the server we're connected to support the specified authentication mechanism? Uses the extension information returned by the server from the EHLO command.

Parameters
auth The authentication mechanism
Returns
  • true if the authentication mechanism is supported

protected static String xtext (String s)

Convert a string to RFC 1891 xtext format.

     xtext = *( xchar / hexchar )

     xchar = any ASCII CHAR between "!" (33) and "~" (126) inclusive,
          except for "+" and "=".

 ; "hexchar"s are intended to encode octets that cannot appear
 ; as ASCII characters within an esmtp-value.

     hexchar = ASCII "+" immediately followed by two upper case
          hexadecimal digits
 

Parameters
s