WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

Samples from Users

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

Email Address Validator using RegEx

 Keywords: SMTP protocol DNS Regular Expressions Syntax VBScript.RegExp Email Address Valid Validate Verify Verifier Validator using RegEx




;***************************************************************************
;**
;**                         Email Validation Script
;**
;** Purpose: validate email addresses using Regular Expression Syntax, DNS and SMTP
;**          This script doesn't attempt to send email to the user.
;**          * Checks the syntax of the email using Regular Expression.
;**          * Executes NSLOOKUP of Mail Exchange (MX) Records on the DNS server.
;**          * Uses Winsock SMTP protocol to contact the domain mailserver and ask if the user is valid
;**
;** Inputs: VBScript.RegExp Object, NSLookup and Winsock Extender
;** Outputs: NA
;** Developer: Deana Falk
;** Revisions:
;** 2009.08.27.001 - initial beta.
;** 2009.09.01.001 - fix: udfEmailValidateAll & udfEmailSyntaxValidator now allows user to specify the regular expression
;**                  matching string pattern to use.
;***************************************************************************

AddExtender("WWWSK44i.DLL") ;WINSOCK Extender

;***************************************************************************
;**
;**                                UDFs
;**
;***************************************************************************

#DefineFunction udfEmailSyntaxValidator( emailaddr, matchflag )
   ;--------------------------------------------------------------------------------;
   ;udfEmailSyntaxValidator : Use Regular expression to validate the syntax of an   ;
   ;                          email address.                                        ;
   ;--------------------------------------------------------------------------------;
   ;emailaddr     : full email address to validate. i.e. test@test.com              ;
   ;matchflag     : 0, 1 or 2 specifies regular expression string matching option   ;
   ;                0 rfc 2822.                                                      ;
   ;                1 www.regular-expressions.info technique.                        ;
   ;                2 match all syntactically valid addresses.                        ;
   ;--------------------------------------------------------------------------------;
   ;returns       : @true if valid, @false if invalid                               ;
   ;--------------------------------------------------------------------------------;
   ;                                                                                 ;
   ;--------------------------------------------------------------------------------;
   retvalue = 0
   regex = ObjectCreate("VBScript.RegExp") ; Creates a regular expression object for use by WinBatch.

   Switch matchflag
      Case 0
         ; The official standard is known as RFC 2822. It describes the syntax that valid email addresses must adhere to.
         ; NOTE: only checks the basic syntax of email addresses.
         pattern='(?:[a-z0-9!#$%%&''*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%%&''*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])'
         regex.IgnoreCase = @TRUE
         Break
      Case 1
         ; This regular expression matches 99% of the email addresses in use today. All the email address it matches can be handled by 99% of all email software out there.
          ; Reference: http://www.regular-expressions.info/email.html
         pattern = '\b[A-Z0-9._%%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'
         regex.IgnoreCase = @TRUE
         Break
      Case 2
         ; Match all syntactically valid addresses. Validator will pass strange looking addresses but the user that it would probably double check the address.
         ; Reference: http://www.markussipila.info/pub/emailvalidator.php
         pattern = '^[a-z0-9,!#\$%%&''\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%%&''\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$'
         regex.IgnoreCase = @TRUE
         Break
   EndSwitch
   regex.Pattern = pattern  ; Required to establish a regular expression pattern to use in searching.

   ret = regex.Test(emailaddr)
   If ret == -1 Then retvalue = @TRUE ; Force -1 result to @true to indicate success
   regex = 0 ; Close Regular Expression Object
   Return retvalue
#EndFunction


#DefineFunction udfGetSTDOUT( cmd )
   ;--------------------------------------------------------------------------------;
   ;udfGetSTDOUT : Get data from StdOut                                             ;
   ;--------------------------------------------------------------------------------;
   ;cmd          : command-shell string to execute                                  ;
   ;--------------------------------------------------------------------------------;
   ;returns      : the data returned to StdOut                                      ;
   ;--------------------------------------------------------------------------------;
   objShell = ObjectCreate("WScript.Shell")
   objWshScriptExec = objShell.Exec(cmd)
   objStdOut = objWshScriptExec.StdOut
   line = objStdOut.ReadAll
   objStdOut = 0
   objWshScriptExec = 0
   objShell = 0
   Return line
#EndFunction

#DefineFunction udfEmailDNSValidator(emailaddr)
   ;--------------------------------------------------------------------------------;
   ;udfEmailDNSValidator : MX (mail exchanger) records to confirm valid domain name ;
   ;--------------------------------------------------------------------------------;
   ;emailaddr     : full email address to validate. i.e. test@test.com               ;
   ;--------------------------------------------------------------------------------;
   ;returns       : name of the mail server or @false if no mail server found       ;
   ;--------------------------------------------------------------------------------;
   ; NOTES: The first real step is to make sure that the domain actually exists.    ;
   ; Finding an MX or A entry in the Domain Name System, or DNS, means that          ;
   ; you're pretty sure that there's a mail server there eagerly awaiting your       ;
   ; emails. This is a huge step towards ensuring the email address is valid!         ;
   ;--------------------------------------------------------------------------------;
   retvalue = @FALSE
   domain = ItemExtract( 2, emailaddr, '@' )  ;'hotmail.com'
   ; TODO: Check list of known good domains/mailservers to speed up the process.
   ;knowndomainarray = "clearwire.net,gmail.com,hotmail.com,ibm.net,ibm.com,microsoft.com,msn.com,netzero.net,winbatch.com,yahoo.com"
   ;mailserverarray = "mail.clearwire.net,mail.gmail.com,etc"
   ;found = ItemLocate( domain, knowndomainarray, ',' )
   ;mailserver = ItemExtract( found, mailserverarray, ','  )
   ;if found then retvalue = mailserver
   ;Execute NSLOOKUP for MX (mail exchanger) records
   cmd = "nslookup -type=mx ": domain
   data = udfGetSTDOUT(cmd)
   ;Pause(cmd,data)
   found = StrIndexNC( data, 'mail exchanger', 1, @FWDSCAN )
   If found
      ;Parse name of mail server from result
      foundptr = found+17
      endptr = StrIndexNC( data, @CRLF, found, @FWDSCAN )
      mailserver = StrSub( data, foundptr, endptr-foundptr )
      retvalue = mailserver
   EndIf
   Return retvalue
#EndFunction

#DefineFunction udfEmailSMTPValidator(fromaddr, emailaddr, mailserver)
   ;--------------------------------------------------------------------------------;
   ;udfEmailDNSValidator : Use the SMTP protocol to contact the domain mailserver   ;
   ;                       and ask if the user is valid                             ;
   ;--------------------------------------------------------------------------------;
   ;fromaddr       : full email address to be passed to remote mailserver           ;
   ;emailaddr      : full email address to validate. i.e. test@test.com              ;
   ;mailserver     : SMTP mail server to validate against. i.e. mail.test.com        ;
   ;--------------------------------------------------------------------------------;
   ;returns        : @true if valid, @false{TAB}ERROR if invalid          ;
   ;--------------------------------------------------------------------------------;
   ; NOTES: some mailservers don't support this feature and other domains accept    ;
   ;        all email users                                                          ;
   ;                                                                                 ;
   ; ERRORS 550 & 553:                                                           ;
   ; Most Internet Service Providers restrict access to their outgoing mail servers ;
   ; to prevent SPAM from being sent through their mail servers. If you are getting ;
   ; the "550 Relay Denied" error message, the outgoing mail server cannot verify   ;
   ; who you are and will not allow you to send mail. Make sure you specify a valid ;
   ; fromaddr.
   ;--------------------------------------------------------------------------------;
   handle = sOpen ()
   If !sConnect (handle, mailserver, '25') ;SMTP port
      Pause('Error Connecting to',mailserver)
      Return @FALSE
   EndIf
   line = sRecvLine (handle, 256)
   ;Pause('Line',line)
   If !udfsmtpCheckReturn(line,220) Then Return @FALSE:@TAB:line
   ;Ask the server for the SMTP extensions that the server supports,
   ;by using the EHLO greeting of the extended SMTP specification (RFC 1870).
   ;fall back to HELO only if the server does not respond to EHLO.
   sSendLine(handle,"EHLO " : mailserver)
   line = sRecvLine (handle, 256)
   ;Pause('EHLO Line',line)
   If !udfsmtpCheckReturn(line,250)
     sSendLine(handle,"HELO " : mailserver)
     line = sRecvLine (handle, 256)
     ;Pause('HELO Line',line)
     If !udfsmtpCheckReturn(line,250) Then Return @FALSE:@TAB:line
   EndIf
   sSendLine(handle,'MAIL FROM: <"': fromaddr : '">')  ;"MAIL FROM: <"anonymous@anonymous.com">
   line = sRecvLine (handle, 256)
   ;Pause('MAIL FROM Line',line)
   sSendLine(handle,'RCPT TO: <"' : emailaddr : '">') ;"RCPT TO: <"test@test.com">
   line = sRecvLine (handle, 256)
   ;Pause('RCPT TO Line',line)
   If !udfsmtpCheckReturn(line,250) Then Return @FALSE:@TAB:line
   ; Clean up
   sSendLine(handle,'RSET')                           ;RSET
   ;line = sRecvLine (handle, 256)
   ;Pause('RSET Line',line)
   sSendLine(handle,'QUIT')                            ;QUIT
   ;line = sRecvLine (handle, 256)
   ;Pause('QUIT Line',line)
   Return @TRUE  ;if you get this far assume sucess
#EndFunction

#DefineFunction udfsmtpCheckReturn(line,number)
   ;--------------------------------------------------------------------------------;
   ;udfsmtpCheckReturn : Check returned message for expected error number           ;
   ;--------------------------------------------------------------------------------;
   ;line             : string returned from e-mail server                           ;
   ;number           : expected error number                                        ;
   ;--------------------------------------------------------------------------------;
   ;returns          : @true if succesful , @false otherwise                          ;
   ;--------------------------------------------------------------------------------;
   ;response = ItemExtract(1,line," ") ; some mailservers don't have a space after the response code.
   response = StrSub( line, 1, 3 ) ; grab first three characters
   Return response == number
#EndFunction


#DefineFunction udfEmailValidateAll( fromaddr, emailaddr, matchflag )
   ;--------------------------------------------------------------------------------;
   ;udfEmailValidateAll : Complete Email Validation                                 ;
   ;--------------------------------------------------------------------------------;
   ;fromaddr      : full email address to be passed to remote mailserver            ;
   ;                   (required by most mailservers)                                 ;
   ;emailaddr     : full email address to validate. i.e. test@test.com              ;
   ;matchflag     : 0, 1 or 2 specifies regular expression string matching option   ;
   ;--------------------------------------------------------------------------------;
   ;returns       : @true if successful , @false otherwise                          ;
   ;--------------------------------------------------------------------------------;
   retvalue = 0
   ; Uses Regular Expressions to Validate email syntax
   ret = udfEmailSyntaxValidator( emailaddr, matchflag )
   If ret
      ; Uses NSLOOKUP to confirm valid DNS ( domain )
      mailserver = udfEmailDNSValidator(emailaddr)
      If mailserver !=@FALSE
         ; Uses WinSock to communicate with SMTP server
         ret = udfEmailSMTPValidator(fromaddr, emailaddr, mailserver)
         If ret==@TRUE
            ;Pause(emailaddr, "SMTP User is Valid")
            retvalue = 1
         EndIf
      EndIf
   Return retvalue
#EndFunction





;***************************************************************************
;**
;**                              MAIN
;**
;***************************************************************************

;---------------------------------------------------------------------------
;                    Initialization Variables
;---------------------------------------------------------------------------
; Specify your email address (most mail servers expect to be passed a valid email)
fromaddr = 'anonymous@anonymous.com'
; Specify email address to be tested
emailaddr = 'test@hotmail.com'

;---------------------------------------------------------------------------
;                    udfEmailValidateAll Function Call
;---------------------------------------------------------------------------
matchflag = 0 ; Use RFC RegEx patttern
ret = udfEmailValidateAll(fromaddr,emailaddr, matchflag)
If ret
   Pause(emailaddr, "Email Address is Valid")
Else
   Pause(emailaddr, "Email Address is Invalid")
EndIf


;---------------------------------------------------------------------------
;                    Individual Function Call Samples
;---------------------------------------------------------------------------
;; Uses Regular Expressions to Validate email syntax
;ret = udfEmailSyntaxValidator( emailaddr, 0 )
;if ret
;   Pause(emailaddr, "Address is Valid")
;   ; Uses NSLOOKUP to confirm valid DNS ( domain )
;   mailserver = udfEmailDNSValidator(emailaddr)
;   if mailserver !=@false
;      Pause(emailaddr, "Domain is Valid.":@CRLF:mailserver)
;      ; Uses WinSock to communicate with SMTP server
;      ret = udfEmailSMTPValidator(fromaddr, emailaddr, mailserver)
;      if ret==@true
;         Pause(emailaddr, "SMTP User is Valid")
;      else
;         Pause(emailaddr, "SMTP User is Invalid":@CRLF:ret)
;      endif
;   else
;       Pause(emailaddr, "Domain is Invalid")
;   endif
;else
;    Pause(emailaddr, "Address is Invalid")
;endif



Exit



Article ID:   W18171
Filename:   Email Address Validator.txt
File Created: 2009:09:22:08:13:40
Last Updated: 2009:09:22:08:13:40