if( configurationManager.isDefaultSmtpServerEnabled() )
{
DefaultSmtpServer[] defaultMXEntries = configurationManager.getDefaultSmtpServers();
for( int index = 0; index < defaultMXEntries.length; index++ ) {
DefaultSmtpServer mxEntry = defaultMXEntries[index];
try {
socket = new Socket( mxEntry.getHost(), mxEntry.getPort() );
username = mxEntry.getUsername();
password = mxEntry.getPassword();
return socket;
}
catch( Exception e ) {
log.debug( "Connection to SMTP Server: " + mxEntry + " failed with exception: " + e ) ;
}
}
}
else {
try
{
// Lookup the MX Entries
// Doing a general lookup, clear DNS passwords.
username = null;
password = null;
Record [] records = new Lookup(domain, Type.MX).run();
if( records == null )
{
records = new Record[0];
log.warn( "DNS Lookup for domain: " + domain + " failed." );
}
// Convert the MX Entries to strings and sort them in order
// of priority.
mxEntries = new String[records.length];
short priority = 0;
short nextPriority = Short.MAX_VALUE;
int mxIndex = 0;
while( mxIndex < mxEntries.length )
{
for (int i = 0; i < records.length; i++) {
MXRecord mx = (MXRecord) records[i];
if( mx.getPriority() == priority )
{
mxEntries[mxIndex++] = mx.getTarget().toString();
if(mxIndex >= mxEntries.length) break;
}
else if( mx.getPriority() < nextPriority && mx.getPriority() > priority )
{
nextPriority = mx.getPriority();
}
}
priority = nextPriority;
nextPriority = Short.MAX_VALUE;
}
}
catch( TextParseException e )
{
throw new RuntimeException( "TextParseException while looking up domian MX Entry: " + e.getMessage() );
}
}
for( int index = 0; index < mxEntries.length; index++ ) {
String mxEntry = mxEntries[index];
int port = 25;
// Extract the server and the port if the syntax server:port is used
int indexPort = mxEntry.indexOf(":");
if (indexPort >= 0) {
try {
port = Integer.parseInt(mxEntry.substring(indexPort+1));
}
catch( Exception e ) {
System.out.println("Invalid defaultsmtpserver port: "+mxEntry.substring(indexPort+1)+" - "+e);
}
if (indexPort==0) {
mxEntry = "localhost";
mxEntries[index] = mxEntry + mxEntries[index];
}
else {
mxEntry = mxEntry.substring(0, indexPort);
}
}
try {
socket = new Socket( mxEntry, port );