JAvaメールアドレスが実際に存在するかどうかを処理するインスタンス

2399 ワード


1.SMTP         :                ;               
     
2.SMTP    /    ,         ASCII  ,  CR LF   。          
            
3.SMTP TCP  25         
4.       
SMTP         (    “  ”    ),        Sock。                   ,          ,              ,                            。
       :
      25  (        ,      )
  helo  
  mail from  ,    250      ,      ,               。
  rcpt to  ,    250   Email  
  quit  ,    

    private static String[] removeInvalidateAddress(String[] addresses, String mailFrom)
    {	
    	ArrayList<String> validateAddresses = new ArrayList<String>();
    	String normalAddress = null;
    	int code;
    	
    	SMTPTransport smptTrans = null;
    	if(StringUtils.isEmpty(mailFrom) || null == addresses)
    	{
    		return new String[0];
    	}
    	String sendCmd = "MAIL FROM:" + normalizeAddress(mailFrom);
    	try
    	{
	    	smptTrans = (SMTPTransport)sendSession.getTransport("smtp");
	    	smptTrans.connect();
	    	code = smptTrans.simpleCommand(sendCmd);
	    	if(code != 250 && code != 251)
	    	{
	    		logger.error("send from invalidate" + mailFrom);
	    	}
	    	else
	    	{
	    		for(String address : addresses)
	        	{
	    			normalAddress = normalizeAddress(address);
	    			String cmd = "RCPT TO:" + normalAddress;
					code = smptTrans.simpleCommand(cmd);
					if(code == 250 || code == 251)
					{
						validateAddresses.add(address);
					}
	        	}
	    	}
    	}
    	catch(MessagingException e)
    	{
    		logger.error("Validate mail address error. send from " + mailFrom, e);
    	}
    	
    	String[] result = validateAddresses.toArray(new String[validateAddresses.size()]);
    	return result;
    }
    
    private static String normalizeAddress(String addr) 
    {
    	if ((!addr.startsWith("<")) && (!addr.endsWith(">")))
    	    return "<" + addr + ">";
    	else
    	    return addr;
    }