001 package railo.runtime.net.mail; 002 003 import java.util.Properties; 004 005 import javax.mail.Authenticator; 006 import javax.mail.MessagingException; 007 import javax.mail.Session; 008 import javax.mail.Transport; 009 010 import org.apache.commons.mail.DefaultAuthenticator; 011 012 import railo.commons.lang.StringUtil; 013 014 /** 015 * SMTP Server verifier 016 */ 017 public final class SMTPVerifier{ 018 019 /** 020 * verify mail server 021 * @param host 022 * @param username 023 * @param password 024 * @param port 025 * @return are the setting ok 026 * @throws SMTPException 027 */ 028 public static boolean verify(String host, String username,String password, int port) throws SMTPException { 029 try { 030 return _verify(host,username,password,port); 031 } 032 catch (MessagingException e) { 033 034 // check user 035 if(!StringUtil.isEmpty(username)) { 036 try { 037 _verify(host,null,null,port); 038 throw new SMTPExceptionImpl("can't connect to mail server, authentication settings are invalid"); 039 } catch (MessagingException e1) { 040 041 } 042 } 043 // check port 044 if(port>0 && port!=25) { 045 try { 046 _verify(host,null,null,25); 047 throw new SMTPExceptionImpl("can't connect to mail server, port definition is invalid"); 048 } 049 catch (MessagingException e1) {} 050 } 051 052 throw new SMTPExceptionImpl("can't connect to mail server"); 053 } 054 } 055 056 private static boolean _verify(String host, String username,String password, int port) throws MessagingException { 057 boolean hasAuth=!StringUtil.isEmpty(username); 058 059 Properties props=new Properties(); 060 props.put("mail.smtp.host", host ); 061 if(hasAuth)props.put("mail.smtp.auth", "true" ); 062 if(hasAuth)props.put("mail.smtp.user", username ); 063 if(hasAuth)props.put("mail.transport.connect-timeout", "30" ); 064 if(port>0)props.put("mail.smtp.port", String.valueOf(port) ); 065 066 067 Authenticator auth=null; 068 if(hasAuth)auth=new DefaultAuthenticator(username,password); 069 Session session = Session.getInstance( props, auth); 070 071 Transport transport = session.getTransport("smtp"); 072 if(hasAuth)transport.connect( host , username ,password ); 073 else transport.connect( ); 074 transport.close(); 075 076 return true; 077 } 078 }